Java has two keywords for managing exceptions: try-catch block.
Java try block :
To contain code that might throw an exception in Java, use a try block. It has to be applied to the technique.
The try block’s remaining statements won’t run if an exception arises at that specific statement. Therefore, it is advised against keeping code in a try block that won’t throw an exception.
The catch or finally block in Java must come after the try block.
Syntax for try-catch block:
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax for try-finally block:
try{
//code that may throw an exception
}finally{}
Java catch block:
Java catch block is used to manage the Exception by defining the type of exception within the parameter. The parent class exception (i.e., Exception) or the generated exception type must be the declared exception. Declaring the created type of exception is, nevertheless, the best course of action.
Example without the usage of try-catch block:
public class TryCatchExample1 {
public static void main(String[] args) {
int data=100/0; //may throw exception
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TryCatchExample1.main(TryCatchExample1.java:5)
Example with the usage of try-catch block:
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zerorest of the code
Example : using try-catch-finally block:
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{ System.out.println("rest of the code");
System.out.println("finally block executed");
}
// rest program will be executed
System.out.println("Outside try-catch-finally clause");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
finally block executed
Outside try-catch-finally clause
Note: also read about the Exception Handling in Java
Follow Me
If you like my post, please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment