What is the "try" keyword in Java?
In this Answer, we’ll learn about the try keyword in Java.
-
We use the
trykeyword totryortest, the code that you think, that the code might have anexception. -
If any
exceptionthrows in the statement inside thetryblock, 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
catchblocks orfinallyblocks.
Syntax:
try
{
//If the code might have an exception.
}
Code:
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");}}}
Explanation:
-
Line 1: First, We created the class
exampleTry -
Line 4: We’ll use the
Initializingvariable tostorevalue. -
Line 5: We’ll initiate the
Tryblock to thecatchexception. -
Line 6: We’ll
Dividethe variable a by b, andstorethe value in a total variable. -
Line 7: Print the
value. -
Line 10: Now, the
catchblock catches theexceptionthrows from the code. -
Line 11: Finally, print the
exception.
Free Resources