Exception Handling in Java Example | Java Exceptional Handling Tutorial

Exception Handling in Java Example | Java Exceptional Handling Tutorial

Exception Handling in Java Example | Java Exceptional Handling Tutorial is today’s topic. In Java, the program that is coded by the programmer can be used in a very unexpected way by the user, due to this, the program may fail in different sort of ways during execution. The main objective of a programmer should be to write a code that does not fail unexpectedly. That unexpected stopping of the program while execution is known as an exception, it disrupts the normal execution flow of a program.

Exception Handling in Java Example

An exception is an event that interrupts the normal flow of execution. It is a disruption during the execution of the Java program. The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained. Let’s see the difference between Error v/s Exception.

#Error V/s Exception

In Java, the error and exception are the quite confusing term most of the time they are taken as the similar term, while they are not.

When a dynamic linking failure or other hard failure occurs in the JVM (Java Virtual Machine), the machine throws an error. When the exception occurred during the execution of the program, this disrupts the flow of program execution.

The following figure is Error.

Error V/s Exception                                                               

The following figure is the Exception.

Exception in Java

#Types of Exception

Exceptions fall under the following two categories.

  1. Checked Exception: These represent exception that is frequently considered “non-fatal” to the program. Must be handled or passed to the parent class. Ex- File not found, Number format conversion, etc.
  2. Unchecked Exception: These are the condition which is “fatal” to the execution of the program. Not much to do with it, the program will terminate with an error message. Ex- Null pointer exception.

#Exception Handling in Java Example

This is the most important feature of Java programming that allows us to handle the runtime error caused by the exception. Java try, catch and finally blocks helps in writing the program code which may throw exceptions in runtime and help us to either recover from exception by changing the flow of the program or handle the exception by reporting it to the user. It helps in preventing application crashes.

#Try Block in Java

Whenever we write a piece of code that might result in an exception, we should use the try block to enclose that piece of code.

#Syntax

try {

  // piece of code

}

#Catch Block in Java

The piece of code we want to execute when a specific exception is raised in the execution of the program should be placed inside the catch block.

#Syntax

try {

  // code may cause exception

}

catch (Exception e) {

   // code that handles the exception
}

#Finally Block in Java

An optional finally block us a chance to run the code which we want to execute every time a try-catch block is completed – either with errors or without any error.

#Syntax

try {

  //code may cause exception
}

catch (Exception e) {
  
  // code that handles an exception

}

finally {

   // default piece of code

}

Exception handling is accomplished through “try-catch” method, or by a “throws” clause.

See the following code example.

public class Example
{  public static int[] arr = new int[5];  
   public static void main(String args[]) {
    try {  
	    
	     arr[7] = 5;  
       }  
      catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("Array index is out of bound");
      }  
      finally{
	 System.out.println("Finally block executed every time");
      }  
   }   
}

See the following output.

Finally Block in Java Tutorial

#try-catch block

When an exception has occurred in the code, the code is laced inside the block with “try” keyword. Just after the try block, the code which handles the exception, if and when it arises, is placed inside the block with “catch” keyword. The moment the exception has occurred the flow of program execution is transferred to the catch block.

See the following code.

public class TryCatchExample2 {

	public static void main(String[] args){
		try
		{
		 String s=null;
                 System.out.println("Length :"+s.length());
		}
		catch(NullPointerException error)
		{
		    System.out.println(error);
		    System.out.println("s cannot be null");
 		}
	}
}

See the following output.

try-catch block example

#Throws

Using throws keyword, we can avoid handling the exception ourselves. This method will throw the exception, and it will be passed up the chain to the parent exception.

See the following code example.

public class TestThrow{
	static void result(int percent){
		if(percent<33)
		   throw new ArithmeticException("Fail");
		else
		   System.out.println("Passed");
	}
	public static void main(String args[]){
		result(30);
		System.out.println("rest of the code");
	}
}

See the following output.

Throws in Java

Finally, Exception Handling in Java Example | Java Exceptional Handling Tutorial is over.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *