Exception Handling Keywords in Java


Java exception handling is managed via five keywords, in this article, we will use all these five keywords with examples.

Let's to understand the basic syntax of try, catch, throw, throws and finally keywords. This diagram summaries usage of these keywords.

Let's list five exception handling keywords and we will discuss each keyword with an example.

1. try Block

Enclose the code that might throw an exception within a try block. If an exception occurs within the try block, that exception is handled by an exception handler associated with it. The try block contains at least one catch block or finally block.

The syntax of java try-catch

try{  
//code that may throw exception  
}catch(Exception_class_Name ref){}  

The syntax of a try-finally block

try{  
//code that may throw exception  
}finally{}  

Nested try block

The try block within a try block is known as nested try block in java.
Why use nested try block?
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.
public class NestedTryBlock {
 
         public static void main(String args[]) {
                 try {
                          try {
                                   System.out.println(" This gives divide by zero error");
                                   int b = 39 / 0;
                          } catch (ArithmeticException e) {
                                   System.out.println(e);
                          }
 
                          try {
                                   System.out.println(" This gives Array index out of bound exception");
                                   int a[] = new int[5];
                                   a[5] = 4;
                          } catch (ArrayIndexOutOfBoundsException e) {
                                   System.out.println(e);
                          }
 
                          System.out.println("other statement");
                 } catch (Exception e) {
                          System.out.println("handeled");
                 }
 
                 System.out.println("normal flow..");
         }
}

2. catch Block

Java catch block is used to handle the Exception. It must be used after the try block only. You can use multiple catch block with a single try.
Syntax:
try
{
      //code that cause exception;
}
catch(Exception_type  e)
{
      //exception handling code
}

catch Block Examples

Let's demonstrate the usage of catch block using ArithmeticException type.
Example 1: ArithmeticException exception type example
public class Arithmetic {

 public static void main(String[] args) {

  try {
   int result = 30 / 0; // Trying to divide by zero
  } catch (ArithmeticException e) {
   System.out.println("ArithmeticException caught!");
  }
  System.out.println("rest of the code executes");
 }
}
Output:
ArithmeticException caught!
rest of the code executes
Example 2: ArrayIndexOutOfBoundsException exception type example
public class ArrayIndexOutOfBounds {

    public static void main(String[] args) {

        int[] nums = new int[] { 1, 2, 3 };

        try {
            int numFromNegativeIndex = nums[-1]; // Trying to access at negative index
            int numFromGreaterIndex = nums[4]; // Trying to access at greater index
            int numFromLengthIndex = nums[3]; // Trying to access at index equal to size of the array
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException caught");
        }

        System.out.println("rest of the code executes");
    }

}
If you have to perform different tasks at the occurrence of different Exceptions, use java multi-catch block.

Multi-catch Block

In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block.
public class TestMultipleCatchBlock {
 public static void main(String args[]) {
  try {
   int a = args.length;
   System.out.println("a = " + a);
   int b = 42 / a;
   int c[] = { 1 };
   c[42] = 99;
  } catch (ArithmeticException e) {
   System.out.println("Divide by 0: " + e);
  } catch (ArrayIndexOutOfBoundsException e) {
   System.out.println("Array index oob: " + e);
  }
  System.out.println("After try/catch blocks.");
 }
}
This program will cause a division-by-zero exception if it is started with no command line arguments, since a will equal zero. It will survive the division if you provide a command-line argument, setting a to something larger than zero. But it will cause an ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the program attempts to assign a value to c[42].
Here is the output generated by running it both ways: Output:
C:\>java MultipleCatches
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultipleCatches TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its superclass.

Catching More Than One Type of Exception with One Exception Handler

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|):
catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

3. throw Keyword

It is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. There are two ways you can obtain a Throwable object: using a parameter in a catch clause or creating one with the new operator.
The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.
Here is a sample program that creates and throws an exception. The handler that catches the exception rethrows it to the outer handler.

Using throw Keyword Example 1

Let's create custom exception ResourceNotFoundException and use throw keyword is used to explicitly throw an exception.
package com.javaguides.exceptions.examples;

public class TestResourceNotFoundException {
 public static void main(String[] args) throws ResourceNotFoundException {
  ResourceManager manager = new ResourceManager();
  manager.getResource(0);
 }

}

class Resource {
 private int id;

 public Resource(int id) {
  super();
  this.id = id;
 }

}

class ResourceManager {
 public Resource getResource(int id) throws ResourceNotFoundException {
  if (id == 10) {
   new Resource(id);
  } else {
   throw new ResourceNotFoundException("Resource not found with id ::" + id);
  }
  return null;
 }
}

class ResourceNotFoundException extends Exception {
    private static final long serialVersionUID = 1L;

    public ResourceNotFoundException(Object resourId) {
        super(resourId != null ? resourId.toString() : null);
    }
}
Output:
Exception in thread "main" com.javaguides.exceptions.examples.ResourceNotFoundException: Resource not found with id ::0
 at com.javaguides.exceptions.examples.ResourceManager.getResource(TestResourceNotFoundException.java:26)
 at com.javaguides.exceptions.examples.TestResourceNotFoundException.main(TestResourceNotFoundException.java:6)
Note that we have used below code to demonstrate usage of throw keyword.
throw new ResourceNotFoundException("Resource not found with id ::" + id);

Using throw Keyword Example 2

Here is a sample program that creates and throws an exception. The handler that catches the exception rethrows it to the outer handler.
package com.javaguides.exceptions.examples;

//Demonstrate throw.
class ThrowDemo {
 static void demoproc() {
  try {
   throw new NullPointerException("demo");
  } catch (NullPointerException e) {
   System.out.println("Caught inside demoproc.");
   throw e; // rethrow the exception
  }
 }

 public static void main(String args[]) {
  try {
   demoproc();
  } catch (NullPointerException e) {
   System.out.println("Recaught: " + e);
  }
 }
}
This program gets two chances to deal with the same error. First, main( ) sets up an exception context and then calls demoproc( ). The demoproc( ) method then sets up another exception-handling context and immediately throws a new instance of NullPointerException, which is caught on the next line. The exception is then rethrown. output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

4. throws Keyword

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing checkup before the code is used.

The syntax of java throws

return_type method_name() throws exception_class_name{  
//method code  
}  
We declare only checked exception using a throws keyword. Let's see an example to demonstrate the usage of a throws keyword.
Basically, whenever exception arises there two cases, either you should handle the exception using try/catch or you declare the exception i.e. specifying throws with the method.

throws Keyword Example

Note that exceptionWithoutHandler(), exceptionWithoutHandler1() and exceptionWithoutHandler2() methods uses throws keyword to declare exception.
public class ExceptionHandlingWorks {

 public static void main(String[] args) {
  exceptionHandler();
 }

 private static void exceptionWithoutHandler() throws IOException {
  try (BufferedReader reader = new BufferedReader(new FileReader(new File("/invalid/file/location")))) {
   int c;
   // Read and display the file.
   while ((c = reader.read()) != -1) {
    System.out.println((char) c);
   }
  }
 }

 private static void exceptionWithoutHandler1() throws IOException {
  exceptionWithoutHandler();
 }

 private static void exceptionWithoutHandler2() throws IOException {
  exceptionWithoutHandler1();
 }

 private static void exceptionHandler() {
  try {
   exceptionWithoutHandler2();
  } catch (IOException e) {
   System.out.println("IOException caught!");
  }
 }
}

5. finally Block

  • Java finally block is a block that is used to execute important code such as closing connection, stream etc.
  • Java finally block is always executed whether an exception is handled or not.
  • Java finally block follows try or catch block.
  • For each try block, there can be zero or more catch blocks, but only one finally block.
  • The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

finally Block Different Scenario Examples

Here is an example program that shows three methods that exit in various ways, none without executing their finally clauses:
// Demonstrate finally.
class FinallyDemo {
 // Throw an exception out of the method.
 static void procA() {
  try {
   System.out.println("inside procA");
   throw new RuntimeException("demo");
  } finally {
   System.out.println("procA's finally");
  }
 }

 // Return from within a try block.
 static void procB() {
  try {
   System.out.println("inside procB");
   return;
  } finally {
   System.out.println("procB's finally");
  }
 }

 // Execute a try block normally.
 static void procC() {
  try {
   System.out.println("inside procC");
  } finally {
   System.out.println("procC's finally");
  }
 }

 public static void main(String args[]) {
  try {
   procA();
  } catch (Exception e) {
   System.out.println("Exception caught");
  }
  procB();
  procC();
 }
}
Output:
inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally
In this example, procA( ) prematurely breaks out of the try by throwing an exception. The finally clause is executed on the way out. 
procB( )’s try statement is exited via a return statement. The finally clause is executed before procB( ) returns. 
In procC( ), the try statement executes normally, without error. However, the finally block is still executed.

finally Block Examples

Example 1: In this example, we have used FileInputStream to read the simple.txt file. After reading a file the resource FileInputStream should be closed by using finally block.
public class FileInputStreamExample {
 public static void main(String[] args) {

  FileInputStream fis = null;
  try {
   File file = new File("sample.txt");
   fis = new FileInputStream(file);
   int content;
   while ((content = fis.read()) != -1) {
    // convert to char and display it
    System.out.print((char) content);
   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if(fis != null){
    try {
     fis.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }
}
Example 2: When we use JDBC connection to communicate with a database. The resource that we have used are ResultSet, Statement, and Connection (in that order) should be closed in a finally block when you are done with them, something like that:
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
    // Do stuff
    ...

} catch (SQLException ex) {
    // Exception handling stuff
    ...
} finally {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) { /* ignored */}
    }
    if (ps != null) {
        try {
            ps.close();
        } catch (SQLException e) { /* ignored */}
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) { /* ignored */}
    }
}

Exception Handling Related Posts

Comments