Exception Handling is the mechanism to handle runtime malfunctions. We need to handle such exceptions to prevent abrupt termination of program. The term exception means exceptional condition, it is a problem that may arise during the execution of program. A bunch of things can lead to exceptions, including programmer error, hardware failures, files that need to be opened cannot be found, resource exhaustion etc.
A Java Exception is an object that describes the exception that occurs in a program. When an exceptional events occurs in java, an exception is said to be thrown. The code that's responsible for doing something about the exception is called an exception handler.
All exception types are subclasses of class Throwable, which is at the top of exception class hierarchy.
Checked Exception: The exception that can be predicted by the programmer.Example : File that need to be opened is not found. These type of exceptions must be checked at compile time.
Unchecked Exception: Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at compile time. Example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked at runtime.
Error: Errors are typically ignored in code because you can rarely do anything about an error. Example : if stack overflow occurs, an error will arise. This type of error is not possible handle in code.
There are given some scenarios where unchecked exceptions can occur.
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0; //ArithmeticException
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
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
If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
int a=new int; a=50; //ArrayIndexOutOfBoundsException
There are 5 keywords used in java exception handling.