It is highly recommended to handle exceptions in Java. The Java code through an exception can occur is known as risky code. By using the try-catch block in Java we can handle exceptions. We have to put risky code inside the try block and corresponding alternative exception handling code in the catch block.
Example-
try{
// risky code
}
catch(Exception e)
{
// alternative exception handling code
}
Java Program without try-catch
public class ExceptionHandling {
public static void main(String[] args) {
System.out.println("without try-catch");
System.out.println(10/0);
System.out.println("Java program without try-catch");
}
}
In the above Java program “Exception in thread “main” java.lang.ArithmeticException: / by zero” occurs when we try to divide a number by zero due to that program terminated abnormally.
Java Program with try-catch block
public class ExceptionHandling {
public static void main(String[] args) {
System.out.println("without try-catch");
try {
System.out.println(10 / 0);
}
catch (ArithmeticException e) {
System.out.println("Cannot divide a number by zero");
}
System.out.println("Java program without try-catch");
}
}
In the above Java program, we handled the exception by using a try-catch block, and the program terminated normally.
Control Flow in try-catch block
conside the follwoing example –
try{
// Statment 1
// Statment 2
}
catch (Exception e){
// Statment 3
}
// Statment 4
Following cases can occur with try-catch block
- If no exception occurs then Statment 1, Statment 2, and Statment 4 will be executed and the program terminate normally.
- If an exception occurs at Statment 2 and the corresponding catch block is matched then Statment 1, Statment 3, and Statment 4 will be executed and the program terminated normally.
- If an exception occurs and there is no corresponding catch block then the program will terminate abnormally.
- If an exception occurs inside the catch block then the program will terminate abnormally.
Note-
- Within the try block if an exception occurs anywhere then the rest of the try block will not be executed. Even though handled that exception. Hence we have to put only risky code inside the try block.
- In addition, to try block, there may be a chance of rising an exception inside catch and finally block.
Similar Java Tutorials
- Odd Even in Java
- Fibonacci Series Java
- Switch statements in Java
- For loop in Java
- While loop in Java
- Do while loop in Java
- Import statement in Java
- Abstract modifier in Java
- Strictfp modifier in Java
- Final variable in Java
- Adapter Class in Java
- Method signature in Java
- Method overloading in Java
- Has A Relationship
- Inheritance in Java
- Encapsulation in Java
- Abstraction in Java
- Data Hiding in Java
- Interface vs abstract class
- Method Overriding in Java
- Method Overloading in Java
- Coupling in Java
9 thoughts on “Exception Handling by Using try-catch in Java”