How to Catch Exceptions in Java?

We understood the basics of Exception in Java, now we will move towards handling these exceptions. We are aware of the fact that when error is detected, an exception is thrown. This means the normal code execution stops and the control are transferred to the catch clause for that exception of the first enclosing try block. The try block might be in the current function (the one that caused the error), or it might be in some function that called the current function (if the current function is not prepared to handle the exception, it is “passed up” the call chain).Furthermore in case no currently active function is prepared to catch the exception, an error message is printed and the execution stops.

Lets elaborate on what we said above.We can connect on FB for more learning!!

How to catch exceptions?

Try Catch in Java
Try-Catch


Using Try-Catch:-

Try Block:-This block is placed around the code that might generate an exception. Therefore try block is one that is used to wrap the exception prone code inside it,making our code protected.

Catch block:- This part have the declaration of the type of exception we are trying to catch. Here we can code for what action need to be taken on exception (Say publishing the error trace or giving error message to user)

Syntax:-

try {
//Our code 
} catch (ExceptionType name) {
name.printStackTrace();
}





Explanation:-
ExceptionType:- declares the type of exception that the handler can handle.


name:-The handler can refer to the exception with name, Java exceptions are objects, so the statements in a catch clause can refer to the thrown exception object using the specified name.

printStackTrace:- It helps us to find the exact error location and name of the method causing the error in our code. In Java execution, each program has the details of its invoking methods onto the execution stack, plus the classes and object names and the line number of the code line that is being executing. Whenever an exception is triggered printStackTrace() can be used to print the contents of the execution stack, and we can fetch the details.

Code:-

Division by Zero 

public class ExceptionHandling {

public static void main(String[] args) {
try {
int a = 1/0;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("We are in the catch block");
}
}

}


Output:-

Divide by Zero Exception caught in Java
Arithmetic Exception

Explanation:-

We are dividing by zero and we are handling that exception using the catch block, in that block we are taking the output of “Stack” which is shown as ArthemeticException:/ by Zero and gives us the line where exception is thrown i.e 6 in our case.


Important Tips:- 

1) We can have multiple Catch blocks, by providing one or more catch blocks directly after the try block.

Syntax:-

try {

} catch (ExceptionType1 name1) {

} catch (ExceptionType2 name2) {

}


2) We can Catch More Than One Type of Exception with only One Exception Handler(Catch). We need to specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|)

Syntax:-

try {
} catch (IndexOutOfBoundsException | IOException e){

}


In this example, the catch parameter e is final(Constant value) and therefore we cannot assign any values to it within the catch block.

3) Arrange multiple, Catch blocks using narrow to broader approach.

For example:- 

catch (I/OException e) {
   //statements to handle this exception 
}
catch (FileNotFoundExcetption e) {
//statements to handle this exception
}


Here incase of some I/O exception (say while working with files) , first block of catch will always be executed irrespective even “FileNotFoundException” is thrown.Beacuse “I/OException” is superclass to “FileNotfoundException” which is the subclass, so our correct order should be:-

catch (FileNotFoundExcetption e) {
//statements to handle this exception
}
catch (I/OException e) {
//statements to handle this exception
}

4) Try-Catch block can also be followed by Finally Block(optional).

  • This block of code always executes, whether or not an exception has occurred.
  •  Only in some exceptional scenarios it might not execute like the thread executing the try or catch code is interrupted or killed, JVM exits while the try or catch code is being executed.
  • It is a good practice to use this block for code cleanup, to free the resources after the execution exits. 
  • The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered

Syntax:-

try
{
//Our code
}
catch(ExceptionType name)
{
}
finally
{
//I will always executes.
}

5) Try block cannot exist without Catch or Final blocks and vice versa.

6) We can create our own exceptions and utilize the throws and throw keyword to initiate that exception.

7) “Exception” class can handle any type of exception, so our handler will look like

Syntax:-
// Common exception handler

catch (Exception e) {
...
}


Note:-Always try to catch specific exceptions. Avoid catching System.Exception whenever possible.

8)Code that detects errors often does not know how to handle them.The best approach is to use exceptions.We catch them using Try-Catch and Exceptions are thrown using a throw statement.

But mostly it is recommend having exception handlers to be as specific as possible,firstly because  a handler must do is determine what type of exception occurred before it can decide on the best recovery strategy, secondly this is general handler and can make code more error-prone by catching and handling exceptions that we never wanted to capture and for which the handler was not intended

What can be done when calling a function that may throw an exception?

1. Catch and handle the exception there itself

Example :- 
Method A calls Method B, and we are catching the exception in Method B itself.

public class ExceptionHandling {
public static void main(String[] args){
//Calling MethodA
MethodA();
}
//MethodA
static void MethodA(){
//Call to MethodB
MethodB();
System.out.println("We are inside MethodA");

}
//MethodB
static void MethodB(){
try {
int a = 1/0;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("We are in the catch block of MethodB");
}
}
}


Output:-

Catch Exception in Java
Catch Exception in the originating Method


2. Catch the exception, then re-throw it or throw another exception

Example :- 
Method A calls Method B, and we are catching the exception in Method B  and throwing another exception.

public class ExceptionHandlingThrow {
public static void main(String[] args){
//Calling MethodA
MethodA();
}
//MethodA
static void MethodA(){
//Handling the thrown Exception
try{
//Call to MethodB
MethodB();
}catch(ArithmeticException e){
System.out.println("We are inside MethodA it will catch Exception");
System.out.println(e.getMessage());
}
}
//MethodB
static void MethodB() throws ArithmeticException{
try {
int a = 1/0;
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("We are in the catch block of MethodB and it will Throw Exception");
throw new ArithmeticException("Exception of Divide by Zero");
}
}
}





Output:-




Throw Exception in Java Example
Throw Exception to the calling Method




3. Ignore the exception (let it "pass up" the call chain).
Example :- 

Method A calls Method B, and we are throwing the exception in Method B and it is catched by Main method

public class ExceptionHandlinginMainMethod {
public static void main(String[] args){
//Calling MethodA
try{
MethodA();
}catch(Exception e){
System.out.println("We are inside Main Function");
e.printStackTrace();

}
}
//MethodA
static void MethodA(){
//Call to MethodB
MethodB();

}
//MethodB
static void MethodB() {
System.out.println("We are inside MethodB it will not catch Exception");
int a = 1/0;
}
}


Output:-

Main method handles Exception in java
Main method handles Exception


Difference between Throw and Throws

Note:- We have taken the code example to explain the difference of Throws and Throw from the above complete code(Point 2)

Throw v/s Throws in Java Selenium
Throw v/s Throws in Java



Why to use Exceptions?

It helps in error handling 🙂 , very simple and straightforward, but it also help us to give structure to our code by separating the “Error-Handed” code from the “Regular code”.

We can group same error types.

For example:-
IOException exception represents any type of error that can occur when performing I/O.On the other hand “FileNotFoundException ” is the subclass of this, which handles only missing file exception.So we can have specific handlers that can handle a very specific exception

catch (FileNotFoundException e) {
...
}

Or to catch all exception based on its group or general type by specifying any of the exception’s superclasses in the catch statement like I/O Exceptions

catch (IOException e) {
...
}
ufthelp

Leave a Reply

Your email address will not be published. Required fields are marked *