For beginners. The content is at the level of "What is exception handling?"
Main.java
public class Main {
public static void main(String[] args) {
int a = 5;
int b = 0;
System.out.println(div(a,b)); //An error occurs here
System.out.println("Finish");
}
static int div(int a, int b) {
return a / b;
}
}
You can compile without any compilation errors. And execute.
Execution result
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.div(Main.java:19)
at Main.main(Main.java:9)
System.out.println(div(a,b));
In the part
java.lang.ArithmeticException: / by zero
After this error
System.out.println("Finish");
Even though there is a process called, the process ends at the part where the error on the line above occurs.
Since the program has been forcibly terminated, it is necessary to write the process ** "If an error occurs, do this" **. This is exception handling.
It's an error. You can simply think of it as an error. Strictly speaking, it seems that the way of thinking differs depending on the person, so it's okay to think that exception handling is error handling for the time being.
Main.java
public static void main(String[] args) {
int a = 5;
int b = 0;
try {
System.out.println(div(a,b));
} catch(Exception e) { //Receive the error as an object called e (object name can be anything)
System.out.println("Divide by 0!");
System.out.println(e); //output e
} finally {
System.out.println("Finish");
}
}
//Calculations that are likely to cause errors. If there is an error, pass the error information to the Exception class.
static int div(int a, int b) throws Exception {
return a / b;
}
}
try{
Error-predicted processing
} catch (Exception e) {
What to do if an error occurs
} finally {
Processing with or without an error
}
When writing a process in which an error is predicted, do not end there, and if an error occurs, perform the process when a partial catch error occurs. With this, the process will move to the end without stopping.
When I actually run it
Divide by 0!//What to do if an error occurs
java.lang.ArithmeticException: / by zero //Error message
Finish//Is running until finally
Recommended Posts