An exception is an event that occurs at run time and disrupts the normal flow of a program’s execution.
The Exception Handling is a mechanism to handle the runtime errors caused by exceptions. Handling an exception is making sure that all the statements execute and the flow of the program doesn’t break.
Exception vs Error :
Exception breaks the flow of the program due to some issues in code while Error breaks the flow of the program due to OS, JVM, Hardware, etc. An exception is recoverable while an error is irrecoverable e.g. OutOfMemoryError, AssertionError, etc
Advantage of Exception Handling :
The advantage of exception handling is that it not only generates exception but also rectify the problem. Exception handling is done where the problem of the source is present.
How it works?
- If an exception has occurred inside a method, the method creates an Object known as Exception Object and hands it off to JVM.
- The exception object contains the name and description of the exception and the current state of the program where the exception has occurred.
- An exception is a process of creating the Exception Object and handling it to the JVM.
- The JVM searches the call stack(ordered list of methods) to find the method that contains a block of code that can handle the occurred exception. The block of the code is called an Exception handler.
- If it finds an appropriate handler(a type of the exception object thrown matches the type of the exception object it can handle) then it passes the occurred exception to it.
- If it couldn’t find the appropriate handler then JVM handover the Exception Object to the default exception handler.
Types of Exception :
- Checked Exception :
- Checked exceptions include the classes which directly inherit Throwable class except for RuntimeException and Error.
- These exceptions are checked at compile-time.
- Eg – IOException, SQLException etc, RemoteException, ClassNotFoundException, InterruptedException, etc.
- Unchecked Exception :
- Unchecked exceptions include the classes which inherit RuntimeException.
- These exceptions are checked at run-time.
- Eg – ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException.
Exception Handling Keywords :
try –
- Try block is where we should place an exception code.
- Either catch or finally, block follows the try block, we can’t use try block alone.
- When JVM gives the try-catch block, the control goes to the end of the try block and after the catch, control goes to OS. When we give our try-catch block, control comes back to us.
catch –
- catch keyword handles the exception.
- We can’t use catch block alone, it must be preceded by a try block.
- It can be followed by finally block later.
- If an exception generated, control goes in catch and then finally block.
- The catch block checks the compatibility. It executes the code and bypassing other catches, it executes the catch of JVM if compatible else only executes the code in the catch of JVM.
finally –
- It is used to execute the important code of the program.
- Its execution is final whether the catch handles an exception or not.
- If it doesn’t generate an exception, through finally block control goes to catch of JVM.
- It is useful in file handling for closing connection.
throw –
- throw keyword throws an exception manually.
- This keyword is followed by an instance of the Exception class.
- We write it in the method body to throw an exception.
- It can throw one exception at a time.
- The line of generation (throw) should be enclosed in a try block followed by an appropriate catch block(pressure handling).
throws –
- throws keyword is used to declare exceptions.
- This works similarly to the try-catch block.
- However, it doesn’t throw an exception.
- In other words, it specifies that there may occur an exception in the method.
- In addition, it is always used with a method signature.
- It is followed by exception class names.
- It can handle multiple exceptions at a time.
- If a method is declared with a throws keyword then it should be called from within a try block followed by a catch block.
To handle exception –
- First of all, identify the line which may cause an exception. —-> z=x/y;
- Then, identify the lines which depend on the line which may cause an exception. —-> System.out.println(z);
- After that, identify the type of exception. ——-> Arithmetic Exception
- Finally, put the identified lines in the try block immediately followed by a catch block with the identified exception class pointer.
public class ExceptionDemo {
//throws keyword
int division(int a, int b) throws ArithmeticException {
int result = a/b;
if(a==0 && b==0) {
//throw keyword
throw new ArithmeticException("Divide by zero error");
}
return result;
}
public static void main(String args[]) {
//try, catch, finally block
try{
//code that may cause exception
int output = 100/0;
OR
System.out.println(division(5,10));
} catch(ArithmeticException e) {
System.out.println(e);
} finally {
System.out.println("Rest of the code....");
}
}
}
Note :
The finally block will always execute even if an exception occurs or if a return statement is present in a method. After the ‘finally’ block execution is completed, control goes back to the return statement in the try block. If there is a return statement in the ‘finally’ block, then the return statements from try/catch blocks will be overridden.