what is Exception Handling?
When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. So, the mechanism used to handle runtime errors are called Exception Handling.
Java exception handling is managed via five keywords:
Keyword | Description |
---|---|
try | The “try” keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can’t use try block alone. |
catch | The “catch” block is used to handle the exception. It must be preceded by try block which means we can’t use the catch block alone. It can be followed by finally block later. |
finally | The “finally” block is used to execute the important code of the program. It is executed whether an exception is handled or not. |
throw | The “throw” keyword is used to throw an exception. |
throws | The “throws” keyword is used to declare exceptions. It doesn’t throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature. |
How do we handle Exception ?
- Exception handling is accomplished through the “try-catch” mechanism, or by “throws” clause in the method declaration.
- For any code that throws a checked exception, you can decide to handle the exception yourself, or pass the exception “up the chain” (to a parent class).
- To handle the exception, you write a “try-catch” block. To pass the exception “up the chain”, you declare a “throws” clause in your method or class declaration.
- If the method contains code that may cause a checked exception, you MUST handle the exception OR pass the exception to the parent class.
Try-catch Mechanism
- Try block
The try block contains set of statements where an exception can occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must be followed by catch blocks or finally block or both.
- Catch block
A catch block is where you handle the exceptions, this block must follow the try block. A single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.
try-catch example:
class Example{
public static void main(String[] arg) {
int x, y;
try{
x = 0;
y = 34/x;
System.out.println(y);
} catch(ArithmeticException e) {
System.out.println("Should not divide number by zero");
}
System.out.println("Out of try-catch block in Java.");
}
}
try with multiple catch blocks example:
class Example{
public static void main(String[] arg) {
try{
int[] x = new int[7];
x[0] = 34/0;
System.out.println("First Print in Try Block");
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException");
}
System.out.println("Out of try-catch block in Java.");
}
}
/************************ OUT PUT ************************/
Arithmetic Exception
Out of try-catch block in Java.
Process finished with exit code 0
- Finally block
- You can attach a finally-clause to a try-catch block.
- The code inside the finally clause will always be executed, even if an exception is thrown from within the try or catch block.
- If your code has a return statement inside the try or catch block, the code inside the finally-block will get executed before returning from the method.
class Example{
public static void main(String[] arg) {
try{
int num =12/0;
System.out.println(num);
} catch (ArithmeticException e) {
System.out.println("Divide by zero error");
} finally {
System.out.println("This will Execute Finally");
}
}
}
/************************ OUT PUT ************************/
Divide by zero error
This will Execute Finally
Process finished with exit code 0
KEY POINTS
- checked & unchecked exception are two type of Exception.
- A checked exception is those exceptions which are the subtype of Exception class but excluding classes which extends Runtime exception.
- A subtype of Error and Runtime Exceptions comes under unchecked Exception.
- Finally block will always be invoked in all condition.
- System.exit() is the only way when finally block will not get executed coz, in that case, JVM will shut down.
- Custom Exception can also be created by extending Exception class.
- Catch block should be ordered in the form of most specific to most general. Otherwise, the compiler will complain about unreachable code.