Exception Handling in Java: The Complete Guide

0
6
Exception Handling in Java Example | Java Exceptional Handling Tutorial

In Java, the program coded by the programmer can be used in a very unexpected way by the user; due to this, the program may fail in different ways during execution.

The main objective should be to write a code that does not fail unexpectedly. This is because that unexpected stopping of the program, while execution is known as an exception, disrupts the normal execution flow.

Exception Handling in Java

Exception Handling in Java handles runtime errors so that the normal flow of the application can be maintained. Let’s see the difference between Error v/s Exception.

An exception is an event that interrupts the normal flow of execution. It is a disruption during the execution of the program. 

Error V/s Exception in Java

In Java, the Error and Exception are quite confusing terms most of the time; they are taken as a 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 occurs during the program’s execution, 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 that is “fatal” to the program’s execution. Not much to do with it; the program will terminate with an error message. Ex- Null pointer exception.

Example

Exception handling 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 help write the program code, which may throw exceptions in runtime and help us either recover from Exception by changing the flow of the program or handle the Exception by reporting it to the user. In addition, 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 code we want to execute when a specific exception is raised in the program’s execution 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 the “try-catch” method or 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

Java try-catch block

When an exception has occurred in the code, the code is laced inside the block with the “try” keyword. Just after the try block, the code which handles the Exception, if and when it arises, is placed inside the block with a “catch” keyword. The moment the Exception has occurred, the program execution flow 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

Java throws

Using the throws keyword, we can avoid handling the Exception ourselves. Instead, 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

That’s it for this tutorial.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.