Tutorial
Before trying to catch a try/catch exception, you must first talk about the Exceptions exception. An exception will be thrown every time an error occurs.
Example:
ArrayIndexOutOfBounds array out-of-bounds error will be thrown when the index does not exist in the array (e. g: Try to get arr [5], but the maximum arr array can only get arr [4]).
An error in ArithmeticError calculation will be thrown when an invalid number operation is performed (e. g: 42/0, not except 0)
Java can throw many exceptions (more than above ).
However, if you are not sure whether an error will occur, how can you handle the exception.
This is the purpose of the try/catch statement! The following is the try/catch Syntax:
Try {// Code here} catch (ExceptionHere name) {// you can handle this exception based on your experience. // if a "ExceptionHere" exception occurs, it will be handled here .}
The code after the try block will try to run. If an exception is thrown in the catch statement code.
You can tell the person using this method that there is a problem or anything else.
Tip: You can also throw an exception and capture it.
Exercise
In this exercise, you will try to make problematic code. I will create a problematic code block. You can use the try statement to include problematic code and then process it in catch.
Tip: An error occurred while using ArrayIndexOutOfBoundsException.
Tutorial Code
public class Main { public static void main(String[] args) { int[] arr = new int[10]; System.out.println(arr[9001]); }}
Solution
public class Main { public static void main(String[] args) { int[] arr = new int[10]; try { System.out.println(arr[9001]); } catch (ArrayIndexOutOfBoundsException ex) { System.out.println("Problem with code detected"); } }}
Note: This article provides simple self-learning materials for my friends based on the documents on multiple websites and the translation of foreign tutorials. You can also update on github and get more information: https://github.com/txidol/interactive-tutorials