January 3, 2024

Exception Handling Tutorial in Java

This Java exception handling tutorial gives an overview of exception handling; what is the Java exception hierarchy, how to write exception handling code and the types of exceptions.

When you write code you don't just code the Happy path as it is only the half of the job. Robust code must make allowance for the unexpected errors. Java programming language provides a robust exception handling mechanism to handle such abnormal condition.

What is exception

An exception can be defined as a condition that disrupts the normal flow of your code. Since exception happens at run time the current code processing can not continue, it needs to handle that exception that's where the exception handler mechanism takes over.

Exception handling may handle that exception by continuing with the flow of the program or show an appropriate message and terminate the application.

How exception handling works in Java

When an exceptional condition happens in any method the procedure for exception handling in Java is as follows-

  • An exception object is created like any other Java object. The exception object encapsulates the information about the error, type of the exception, where exception happened.
  • The execution of the code in the method is stopped and created exception is thrown.
  • The exception handling mechanism looks for the exception handler that can handle the thrown exception. The method where exception is thrown may handle that exception itself or leave it to the calling method to handle it.
  • If no exception handler is provided for the thrown exception, default exception handler will be called to handle that exception. Default exception handler prints the stack trace from the point exception was thrown and terminates the program.

How exception handling is managed in Java

Java programming language provides five keywords try, catch, finally, throw and throws for handling the exceptions in Java applications.

  1. try– If you want to handle the exception thrown in a method with in that method itself, you need to provide try-catch block for handling that exception. The code that may throw an exception is enclosed with in the try block.
  2. catch– You enclose the code that may throw an exception in try block but how about handling the exception when it is thrown. For that you provide a catch block which follows the try block.
  3. finally– If you have any code that must execute after the try block is completed you can put that in finally block. Code in finally block is always executed whether an exception is thrown in try block or not.
  4. throw– Exception can be thrown by the Java run time or you can throw an exception manually too. If you want to throw an exception manually you can do it using throw. For example
    if(obj == null){
       throw new NullPointerException("Null reference");
    }
  5. throws– If you don't want a method to handle the exception it may throw itself, you can specify those exception using the throws clause. For example–
    void readFile() throws IOException{
       ....
       ....		
    }

try-catch-finally block in exception handling

A try-catch-finally block in Java has the following form-
try {
   // Code that may throw excpetion
}
catch (ExceptionType1 exp){
   // Exception handler for  ExceptionType1
}
catch(ExceptionType2 exp){
  // Exception handler for  ExceptionType2
}
finally{
  // code that has to be executed after try block completes
}

Exception Hierarchy in Java

In Java exception hierarchy all exception types are subclasses of Throwable class. Just below Throwable in Java exception hierarchy are two subclasses that divide exception into two different branches. These subclasses are Exception and Error.

Error– Error and its subclasses define exceptions that your program cannot handle, like out of memory error. As example – StackOverflowError, OutOfMemoryError.

Exception– Exception and its subclasses defines exception that a program can handle. An important subclass of Exception is RuntimeException, all the unchecked exceptions are subclasses of RuntimeException.

Java Exception Hierarchy

Types of Exceptions

As per Java docs there are three types of exceptions in Java exception handling-

  1. Checked Exceptions– These are the exceptions that a code should be able to anticipate and recover from. Java compiler would even force you to put the code that is anticipated to throw checked exception with in a try-catch block or specify it using throws. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.
  2. Error- The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. As example– If your application has to read a file and it opens that file but unable to read it because of some OS related problem or hardware problem which is external to your application. In this case the unsuccessful read will throw java.io.IOError.
  3. Runtime exceptions- These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. Logical errors or improper use of API in your code will result in runtime exception. As example- If you are calling a method on the passed String object i.e. str.substring() but the passed String is null. That will result in null pointer exception at run time.

Java compiler doesn't enforce use of try-catch block or throws clause for Runtime exceptions. Out of the above three types of exceptions Errors and runtime exceptions are collectively known as unchecked exceptions.

Refer Difference Between Checked And Unchecked Exception in Java to see the difference between checked and unchecked exceptions in Java.

Advantages of Exception handling in Java

  1. Exception handling in Java provides a mechanism to gracefully recover from run time errors.
  2. Provides better design by separating the code that has your logic from the code that handles exception.

That's all for the topic Exception Handling Tutorial in Java. If something is missing or you have something to share about the topic please write a comment.

You may also like

No comments:

Post a Comment