Java has two keywords for managing exceptions: try-catch 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.
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
try{
//code that may throw an exception
}finally{}
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.
public class TryCatchExample1 {
public static void main(String[] args) {
int data=100/0; //may throw exception
System.out.println("rest of the code");
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TryCatchExample1.main(TryCatchExample1.java:5)
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");
}
}
java.lang.ArithmeticException: / by zerorest of the code
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");
}
}
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
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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…