Exception handling in Java

Exception Handling in Java

Exception handling in Java is a process that aims at handling the worse state in a program to avoid a system crash. An exception is a state while running the program that happens when an unexpected point occurs which requires special processing. It gracefully handles the situation by showing an error message saving the crash and program breakage. In case these exceptions are not handled properly, the program might terminate badly. Exception handling might change the state of flow of a program.  

To Know About Scanner Class in Java

Exception Handling Examples

For example, in code, if we divide a number by zero, it surely will compile successfully. But it will throw a run time exception because of which applications will be terminated abruptly.

Following are the features of exception handling in java:

  • It separates the regular code from the error code to handle the errors properly. It is done by using the if-else condition.
  • Exception handling groups the error types together so that it is easy to work on the groups.
  • It makes sure that the definite flow of the program remains the same when an exception occurs.
  • A function can throw as many exceptions as it wants but handles the selected ones only.

Types of Exceptions in Java:

As we know that there are two types of exceptions in Java: Built in and user defined. Let us first discuss built-in exceptions. These are the ones already available in Java library:

  • ArithematicException: When there is an error in the arithmetic operation of the program, the program throws an ArithematicException. For example, if we try to divide a number by 0.
  • ArrayIndexOutOfBoundsException: If the user tries to insert a wrong value in a wrong place, the program tends to thrown an ArrayIndexOutOfBoundsException. For example the index is either negative or bigger than the array size.
  • FileNotFoundException: When the user is unable to find a file or unable to open a file, the program throws FileNotFoundException.
  •  RunTimeException: RunTimeException is an error which occurs during the run time. 
  • ClassNotFoundException: When the user is unable to find a class or if he is unable to access a class, the program thrown ClassNotFoundException.
  • NumberFormalException: Due to some error, sometimes it is not possible to convert a string into number format. Then the program throws NumberFormalException.
  • StringIndexOutOfBoundsException: This exception is only thrown by a string class when the index of elements goes negative or it exceeds the size of the string.

Syntax of Try Catch Block

try {

}
catch(Exception e){

} 

Below is a simple example for better understanding of exception handling:

public class MyClass {
public static void main(String[] args) 
{
    try {
	 int [] myWords = {1, 2, 3};
	 System.out.println(myWords[10]);
	}
    catch(Exception e)
    {
     System.out.println("The program is not right");
    }
}
}

The output will be:

The program is not right

Types of Errors

  • Run time errors: This exception creates a problem in the normal execution of the program. Like the example, we discussed above dividing a number by zero. The system gets crashed in most of the cases.
  • Compile-time errors: The exceptions that occur during the time of compiling are called compile-time errors. It could include reference, errors in syntax, and class import.

We have a block in java for error handling. It has 5 methods try, catch and throw, throws and finally.

Try block: the part of the program which is able to throw an exception is put inside the try block. If there comes any exception inside the try block, it is taken care of in catch block.

Catch block: this block handles the exception that is thrown by try block. There can be more than one catch block in the program depending upon the types of exceptions. It is simple to place a catch exception handler where we want to handle the exception.

Throw block: the block where the problem shows up in the code is the throw block. It communicates the problem about the error.

Throws block: We use throws block when we want to declare more than one exception. These can possibly be separated by commas.

Finally block: This block contains those statements which execute whether exceptions occur or not. As we know that the statement always gets executed even when an exception occurs or not. To sum up with, finally block always executes.

Below is an example that shows the correct usage of try, catch and throw blocks.

public class ExceptionExample
{
  public static void main(String args[])
  {
	int x,y,z;
 	try {
	   x= 0;
	   y= 2;
	   z= y/x;
	   System.out.println("The code will not be executed");
       }
       catch(Exception e)
       {
 	 System.out.println("The number is divided by zero");
       }
    System.out.println("The exception is handled");
  }
}


The above program compiles successfully but will show an error during run time. This is because we are trying to divide a number by 0, which is practically not possible.

The output will be:

The number is divided by zero
The exception is handled

This works as an exception handler checks the divisor first. If the divisor is zero, it throws the exception otherwise it prints the correct result. This helps in saving the system from any crash. The exception is thrown in try block but is handled under catch block.

Leave a comment

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

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Java Online Quiz

Level up your coding skills with our interactive programming quiz!