In this Answer, we’ll learn about the try keyword in Java.
We use the try keyword to try or test, the code that you think, that the code might have an exception.
If any exception throws in the statement inside the try block, it should be handled. The rest of the code will not execute further.
If the code has or throws any exception it should be handled by using catch blocks or finally blocks.
try
{
//If the code might have an exception.
}
class exampleTry {public static void main(String[] args){int a = 10, b = 0, total;try {total = a / b;System.out.println("result" + total);}catch (ArithmeticException e) {System.out.println("Exception: The code tries to divide the number by zero");}}}
Line 1: First, We created the class exampleTry
Line 4: We’ll use the Initializing variable to store value.
Line 5: We’ll initiate the Try block to the catch exception.
Line 6: We’ll Divide the variable a by b, and store the value in a total variable.
Line 7: Print the value.
Line 10: Now, the catch block catches the exception throws from the code.
Line 11: Finally, print the exception.
Free Resources