Try Catch
Try Catch
Try...Catch
Java Exceptions
When executing Java code, different errors can occur:
coding errors made by the programmer, errors due to
wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and
generate an error message. The technical term for this
is: Java will throw an exception (throw an error).
Java try and catch
✔ The try statement allows you to define a block of code to be tested for errors
while it is being executed.
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Example
This will generate an error, because myNumbers[10] does not exist.
Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 10
at MyClass.main(MyClass.java:4)
Try and Catch
If an error occurs, we can use try...catch to catch the error and execute some code to handle it: