Exception Handling in Java
Exception Handling in Java
Exception Handling in Java
1. Exception Handling
2. Advantage of Exception Handling
3. Hierarchy of Exception classes
4. Types of Exception
5. Exception Example
6. Scenarios where an exception may occur
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the
normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and
unchecked exceptions.
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the
code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform
exception handling, the rest of the statements will be executed. That is why we use exception handling
in Java.
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as
checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions
are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError
etc.
Keyword Description
JavaExceptionExample.java
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException