Site icon TestingDocs.com

Exceptions in Java Programs

Overview

In this post, we will discuss Exceptions in java programs. First of all, if the code can throw more than one kind of exception, then we can have several catch clauses with a single try to catch multiple exceptions.

Exception Hierarchy

 

 

As shown in the above picture, the blue ones are checked exceptions and the red ones are unchecked exceptions.

The most specific ones should be listed first, and the more general ones later. Also, exceptions are objects from classes in java. Here, more general means a super class, and more specific means a sub class.

Therefore, we have to handle the more specific exceptions first and then the generic ones. Additionally, if we reverse we might end up writing unreachable code as shown below :

 

 

Exception already handles the NullPointerException because it is the super class.

When an exception is thrown in a try block, the execution of the try is abandoned immediately and the system searches for a handler known as catch block in java, of the type of the exception that was thrown. Also, it’s common misconception that try block is continued after exception. However, it’s NOT the case as shown in the below picture.

 

 

Checked Exceptions and Unchecked Exceptions

There are two basic kinds of exceptions, Exception and RuntimeException as shown in the above picture.

Exception, is one that can occur even in a correct program. For example, when we try to create a file, the operating system may not permit it, perhaps because the disk is locked, or there is no space available. Also, these kinds of problems are beyond the control of the programmer. Therefore, even a correct program can generate them. For this reason such exceptions must be caught by the programmer. The IOException is an example. So, they must be caught.

 

In addition, a null pointer exception is a run-time exception and these need not be caught. Hence, a correct program should never have any of these, so if you have one, you need to fix your program.

Sample code with multiple catch blocks

public class MultipleExceptions {
    
    public static void main(String[] args) {
        PrintWriter writer = null;
        try
            {     
            writer = new PrintWriter(new FileWriter("?.txt"));
            } 
          catch (IOException ioe) {
                System.out.println("IOException");
            }
           catch (Exception e) {
            System.out.println("Exception");
            }
        
        finally
            {
            System.out.println("This will be executed always");
            }
        
    }

}

 

Handle Multiple Exceptions

https://www.testingdocs.com/handle-multiple-exceptions-in-java/

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version