During the execution of Java code, various errors may arise, including coding errors made by the programmer, errors stemming from incorrect input, or unforeseen circumstances.
When an error arises, Java typically halts and generates an error message. This process is technically termed as Java throwing an exception (or throwing an error).
The try statement enables you to specify a block of code to be evaluated for errors during its execution.
The catch statement permits you to specify a block of code to be executed if an error arises within the try block.
The try and catch keywords are used in pairs.
try { |
Take into account the following example:
An error will be triggered because myNumbers[10] does not exist.
public |
The output is expected to resemble the following:
|
In the event of an error, we can employ try…catch to capture the error and execute specific code to manage it.
public |
The output is expected to be:
|
The finally statement enables the execution of code after try…catch, regardless of the outcome:
public |
The output is expected to be:
Something went wrong. The ‘try-catch’ block has completed. |
The throw statement permits you to generate a custom error.
The throw statement is employed alongside an exception type. Java offers numerous exception types, including ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, and more.
If the age is below 18, throw an exception (print “Access denied”). Otherwise, if the age is 18 or older, print “Access granted”.
public
|
The expected output is:
Exception in thread “main” java.lang.ArithmeticException: Access denied – You must be at least 18 years old. at Main.checkAge(Main.java:4) at Main.main(Main.java:12) |
If the age were 20, no exception would be encountered.
checkAge(20);
|
The expected output is:
|