What is Java exception handling?
Exception handling assures that the flow of the program doesn’t break when an exception occurs. In the previous tutorial, we understood that an unexpected exception can interrupt the normal flow of the program and the program/application may terminate abnormally. To overcome this problem Java provides a powerful mechanism called exception handling.
Java exception hierarchy
The Java class Throwable is the root of Java exception hierarchy similarly, class Exception is the root of all other exception classes.
Exception handling keywords
Following are the 5 different keywords to deal with exception handling in Java –
- try
- catch
- finally
- throw
- throws
We will see and understand each of them in the next tutorials.
Checked exception handling
In the previous tutorial, we have seen the checked exception, where the exception occurs when we try to read a non-existing file. Let’s see how to handle it and let the user know about it without breaking the flow of the program.
import java.io.FileNotFoundException; import java.io.FileReader; public class ExceptionHandlingExample1 { public static void main(String[] args) { // Start exception handling block try { String fileName = "sample.txt"; FileReader reader = new FileReader(fileName); } catch (FileNotFoundException ex) { // Tell the user about exception System.out.println("File [sample.txt] not found!"); System.out.println("Invalid file provided!"); } // End exception handling block System.out.println("Application terminated!"); } }
Unchecked exception handling
The following program shows how you can handle an unchecked exception. In the previous tutorial, we have seen the unchecked exception, where the exception occurs when we try to divide a number by 0. Let’s see how to handle it and let the user know about it without breaking the flow of the program.
public class ExceptionHandlingExample2 { public static void main(String[] args) { int numA = 10; int numB = 0; // Start exception handling block try { System.out.println(numA / numB); } catch (ArithmeticException ex) { // Tell the user about exception System.out.println("Divide by zero!"); System.out.println("Invalid number provided!"); } // End exception handling block System.out.println("Application terminated!"); } }