Objective: In the previous article Interface in Java we have learned about the Interfaces, Extending Interface and Extending Multiple Interface. In this article we will learn about the Exception in Java.
Exceptions:
In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
There are two types of Exceptions in Java:
-
1.Checked Exceptions
-
2.Unchecked Exceptions
-
3.Error
1. Checked exception: The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions.
e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
2. Unchecked Exception: The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
There are given some scenarios where unchecked exceptions can occur. They are as follows:
- ->Arithmetic Expression:
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
-
->Null Pointer Exception:
If we have null value in any variable, performing any operation by the variable occurs an ->NullPointerException
String s=null;
System.out.println(s.length());//NullPointerException
-
->Number format Exception:
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur ->NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
-
->ArrayINdexOutOfBound Exception:
If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
3. Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Exception Handling in Java:
There are 5 keywords used in java exception handling.
-
1. try
-
2. catch
-
3. finally
-
4. throw
-
5. throws