In: Computer Science
What is Try and Catch in Java with example?
A TRY block contains the program statement in which an exception can occur. Also a TRY block is always followed by CATCH block which is used to handle the exceptions that occur in TRY block. A TRY block is always followed by CATCH block.
A CATCH block is associated with a TRY block and the corresponding CATCH block is executed if an exception occurs in the try block.
Below is the JAVA Program to Explain the Try Catch Code
class TryCatch {
public static void main(String args[]) {
int number1, number2,number3;
try {
// Try block to handle
code that may cause exception
number1 =
0;
//We Assign Number 1 with
0
number2 =
65;
//We Assign Number 2 with 65
number3 = number2 /
number1; //Now we try to divide 65 by 0 which should
through an exception
//and will be caught in catch block
System.out.println("Try
block message");
} catch (ArithmeticException e) {
// This block is to catch exception for divide-by-zero error
System.out.println("Error: Don't divide a number by zero");
}
System.out.println("I'm out of try-catch
block in Java.");
}
}
When Exception Caught