Environment: Windows10, Eclipse, java8
Describes exception handling using try catch finally in java.
try{
processing
}catch(Exception type Argument){
Processing when an exception occurs
}finally{
Last action to be executed(With or without exception)
}
public static void main(String[] args) {
double a = 99999;
//----------Cases where exception handling occurs----------
System.out.println("-----Exception occurred-----");
try {
a = 30/0;
}catch(ArithmeticException e) {
System.out.println("Exception handling: 0 does not break");
System.out.println(e);
}finally {
System.out.println("finally "+ "a="+a);
}
//----------Case where exception handling does not occur----------
System.out.println("-----normal-----");
try {
a = 30/3;
}catch(ArithmeticException e) {
System.out.println("Exception handling: 0 does not break");
System.out.println(e);
}finally {
System.out.println("finally "+ "a="+a);
}
}
-----Exception occurred-----
Exception handling: 0 does not break
java.lang.ArithmeticException: / by zero
finally a=99999.0
-----normal-----
finally a=10.0
In the above program, on the line a = 30/0; An exception (ArithmeticException) has occurred because we are dividing by zero (there is no solution). Therefore, the following processing is executed.
}catch(ArithmeticException e) {
System.out.println("Exception handling: 0 does not break");
}
Therefore, as the execution result, "Exception handling: 0 does not break" is displayed.
How should I write the contents of catch?
}catch(ArithmeticException e){
In the above example, ArithmeticException is an exception that is thrown when divided by zero.
Other exceptions can be written in the following form, so I will explain them.
}catch(Exception type Argument){
Write the type that will be thrown when an exception occurs.
Check the exception handling corresponding to the processing written in try in the reference and use it. For java11: https://docs.oracle.com/javase/jp/11/docs/api/index-files/index-1.html
Also, if you want to handle exceptions in file I / O operations, etc. When using an exception called IOException
import java.io.IOException;
You may also need to import the package with.
Regarding the exception called ArithmeticException this time,
import java.lang.ArithmeticException
It seems that it is necessary to write and import. However, java.lang is implicitly imported within the compiler and does not need to be written. By the way, this is why System.out.println can be used without import.
You can name it freely. "E" is often used.
In this example Because it describes "System.out.println (e);" "Java.lang.ArithmeticException: / by zero" in the execution result Is displayed, and it can be confirmed that an exception has been received.
Recommended Posts