For those who have just started learning programming including the Java language, and those who have already learned it, for review This time I'm writing to learn about ** exception handling **.
[Introduction to Java Table of Contents] -Variables and types ・ Type conversion -Variable Scope -String operation -Array operation ・ Operator ・ Conditional branch (in preparation) ・ Repeat processing (in preparation) ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation) ・ About exception handling ← Now here ・ About lambda expression ・ About Stream API
If there is a grammatical error in the source code, an error will be output at the time of compilation and it cannot be executed, so it is possible to correct the grammatical error or error.
However, an error that is not known at the time of compilation but is noticed after execution is called an exception.
-Trouble in the execution environment or situations that cannot be dealt with by the program ** Error ** ・ Exclusions that can be dealt with by the program **
In order to prevent the above-mentioned unexpected operation (exception), the corresponding processing is called ** exception handling **.
・ Throwable ← Error, exception superclass (parent class)
Subclasses (child classes) of the Throwable class ・ ** Error class ** ・ ** Exception **
Subclasses (child classes) of the Exception class ・ ** RuntimeException class ** ・ ** Other classes **
The RuntimeException class also has subclasses (child classes).
try-catch First, let's write the code normally.
Main.java
class Error {
public static void main(String[] args) {
String[] fruits = {"Apple", "banana", "Mandarin orange"};
//Extract the fruits array one by one, but try to access outside the elements of the array
for(int i = 0; i < 4; i++) {
System.out.println(fruits[i]);
}
System.out.println("Displayed all fruits");
}
}
Output result
Apple
banana
Mandarin orange
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Main.main(Main.java:6)
It was displayed as above. The last "Display all fruits" is not output and the program ends in the middle.
Next, let's modify the above code using the try-catch statement.
In the try block
, describe the place where the exception is likely to occur.
Write catch (exception class name variable name)
and
In the catch block
, describe the processing when an exception occurs.
Main.java
class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "banana", "Mandarin orange"};
try {
//Processing that is likely to cause an exception
for(int i = 0; i < 4; i++) {
System.out.println(fruits[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {
//What to do when an exception occurs
System.out.println("Exception occured");
}
System.out.println("Displayed all fruits");
}
}
When you run
Output result
Apple
banana
Mandarin orange
Exception occured
Displayed all fruits
It was output as above. An exception has occurred in the 4th loop and the processing inside the catch block is being executed. And, the program is output until the last "display all fruits" without terminating in the middle.
finally
In the finally block
, describe the process that you want to execute regardless of whether an exception occurs or not.
If no exception is raised (access inside the elements of the array)
Main.java
class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "banana", "Mandarin orange"};
try {
//Processing that is likely to cause an exception
for(int i = 0; i < 3; i++) {
System.out.println(fruits[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {
//What to do when an exception occurs
System.out.println("Exception occured");
} finally {
//Always executed with or without exceptions
System.out.println("Be sure to process");
}
System.out.println("Displayed all fruits");
}
}
When you run
Output result
Apple
banana
Mandarin orange
Be sure to process
Displayed all fruits
The processing in the finally block is executed as described above.
The next time an exception occurs (accessing outside the elements of the array)
Main.java
class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "banana", "Mandarin orange"};
try {
//Processing that is likely to cause an exception
for(int i = 0; i < 4; i++) {
System.out.println(fruits[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {
//What to do when an exception occurs
System.out.println("Exception occured");
} finally {
//Always executed with or without exceptions
System.out.println("Be sure to process");
}
System.out.println("Displayed all fruits");
}
}
When you run
Output result
Apple
banana
Mandarin orange
Exception occured
Be sure to process
Displayed all fruits
It was output as above. An exception is thrown and the processing inside the catch block is executed. Then, the processing in the finally block is executed, and the output is up to the last "display all fruits".
As a combination of writing style, as above ・ Try-catch ・ Try-finally ・ Try-catch-finally Is OK!
The following writing method will result in a compile error.
・ Try block only
Main.java
class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "banana", "Mandarin orange"};
//Only try blocks are compile errors
try {
for(int i = 0; i < 4; i++) {
System.out.println(fruits[i]);
}
}
System.out.println("Displayed all fruits");
}
}
・ Try-finally-catch, catch-finally-try
Main.java
class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "banana", "Mandarin orange"};
// try-finally-catch is a compile error
try {
for(int i = 0; i < 4; i++) {
System.out.println(fruits[i]);
}
} finally {
System.out.println("Be sure to process");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occured");
}
// catch-finally-try also compile error
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occured");
} try {
for(int i = 0; i < 4; i++) {
System.out.println(fruits[i]);
}
} finally {
System.out.println("Be sure to process");
}
}
}
I learned exception handling by try-catch-finally block as an exception handling method, Let's touch on the types of exceptions here and learn when to actually use them.
** Unchecked exception ** An exception in which the compiler does not check whether exception handling is described (exception handling is optional) The target is the RuntimeException class and below.
Exception handling is optional, so there is no problem with the java syntax itself and you can compile it.
Main.java
class Main {
public static void main(String[] args) {
int[] num = {10, 20, 30};
System.out.println(num[3]); //Trying to output outside the range of the num array
}
}
When you compile and run the above file
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Main.main(Main9.java:71)
I'm getting an exception for ArrayIndexOutOfBoundsException, a subclass of RuntimeException. The exception is that the array index (subscript) is out of range.
Normally, exception handling is not performed because such exceptions can be prevented by the programmer checking at the time of coding. (If you write exception handling in all the places where exceptions are likely to occur, it will be complicated code)
But for the time being, I will enclose it in a try-catch statement.
Main.java
class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "banana", "Mandarin orange"};
int[] num = {10, 20, 30};
try {
System.out.println(num[3]); //Trying to output outside the range of the num array
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occured");
}
}
}
When you compile and run it
Exception occured
The processing in the catch statement is being executed.
** Inspection exception ** An exception in which the compiler checks whether exception handling has been described (exception handling must be described) Other classes other than RuntimeException are targeted.
The description of exception handling is mandatory, and if there is no description, an error will occur at compile time. Let's take a look.
When there is no description of exception handling.
Main.java
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
class Main {
public static void main(String[] args) {
//Specify the file path
File file = new File("test.text");
//Get one line from the contents of the file
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String str = bufferedReader.readLine();
//Turn the loop and display line by line
while(str != null){
System.out.println(str);
str = bufferedReader.readLine();
}
//Finally close the file to free resources
bufferedReader.close();
}
}
When you compile this,
Main.java:13:error:The exception FileNotFoundException is not reported. Must be captured or declared to throw
FileReader fileReader = new FileReader(file);
^
Main.java:15:error:Exception IOException is not reported. Must be captured or declared to throw
String str = bufferedReader.readLine();
^
Main.java:20:error:Exception IOException is not reported. Must be captured or declared to throw
str = bufferedReader.readLine();
^
Main.java:24:error:Exception IOException is not reported. Must be captured or declared to throw
bufferedReader.close();
^
4 errors
If you compile without describing exception handling, a compile error will occur.
Next, enclose it in a try-catch statement.
Main.java
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
class Main {
public static void main(String[] args) {
// try-When catch exception handling is described
try {
//Specify the file path
File file = new File("test.text");
//Get one line from the contents of the file
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String str = bufferedReader.readLine();
//Turn the loop and display line by line
while(str != null){
System.out.println(str);
str = bufferedReader.readLine();
}
//Finally close the file to free resources
bufferedReader.close();
} catch (IOException e) {
System.out.println("Exception occured");
}
}
}
When I compile, I don't get a compile error. When you run
AIUEO
Kakikukeko
SA Shi Su Se So
And the contents of the test.txt file are output.
This time, I intentionally make a mistake in the path specification part of the file.
Main.java
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
class Main {
public static void main(String[] args) {
// try-When catch exception handling is described
try {
//Specify the file path
File file = new File("aaaaaaaaa.text"); //Specify a text file that does not exist
//Get one line from the contents of the file
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String str = bufferedReader.readLine();
//Turn the loop and display line by line
while(str != null){
System.out.println(str);
str = bufferedReader.readLine();
}
//Finally close the file to free resources
bufferedReader.close();
} catch (IOException e) {
System.out.println("Exception occured");
}
}
}
You can compile. When I run it,
Exception occured
Was output. An exception has occurred and the processing in the catch statement is being executed.
As mentioned above, in the case of other classes other than RuntimeException, you have to be aware that there are cases where a compile error will occur if exception handling is not described.
②throws
In addition to the try-catch-block block exception handling, you can use the throws keyword to handle exceptions.
This keyword is used when defining a method that can raise an exception.
By specifying throws exception class name that occurs
The mechanism is such that the exception is forwarded to the caller of this method.
Specifically, I will try to make a method based on the above sample code.
Define the operation to read and output the file as a method in another class.
Use the throws keyword
when defining this method.
GetText.java
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
class GetText {
//The method specified by throws throws the exception to the caller
public void getText() throws IOException {
//Specify the file path
File file = new File("aaaaaaaaa.text"); //Specify a text file that does not exist
//Get one line from the contents of the file
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String str = bufferedReader.readLine();
//Turn the loop and display line by line
while(str != null){
System.out.println(str);
str = bufferedReader.readLine();
}
//Finally close the file to free resources
bufferedReader.close();
}
}
When calling the getText method in Main.java, if an exception occurs, the catch statement described here will be processed.
Main.java
import java.io.IOException;
class Main {
public static void main(String[] args) {
//At the time of throws
try {
GetText gt = new GetText();
//Call the getText method using the throws keyword
gt.getText();
//Catch the exception
} catch (IOException e) {
System.out.println("Exception occured");
}
}
}
If you compile this file, you can compile it. Just run it
Exception occured
I got an exception to access a file that doesn't exist in getText. However, there is no description of try-catch statement in the method being processed.
By declaring throws exception class name
when defining the method,
An exception is thrown (thrown) in the catch statement in the caller of this method, and exception handling is performed.
By the way, try eliminating the try-catch statement at the method caller,
Main.java
import java.io.IOException;
class Main {
public static void main(String[] args) {
//At the time of throws, try-When the catch statement is deleted
GetText gt = new GetText();
gt.getText();
}
}
When you compile ...
Main.java:16:error:Exception IOException is not reported. Must be captured or declared to throw
gt.getText();
^
1 error
I get a compile error. Note that even if you define a method that uses the throws keyword, a compile error will occur if the caller of the method does not describe exception handling using the try-catch statement.
③throw
You can explicitly throw an exception in your program using the throw keyword
.
The difference from throws is that throws catches when an exception occurs, but throws explicitly catches an exception.
Therefore, you can intentionally raise an exception yourself.
Main.java
class Main {
public static void main(String[] args) {
int[] num = {10, 20, 30};
try {
for(int i = 0; i < num.length; i++) {
System.out.println(num[i]);
if(num[i] < 20) {
//Explicitly throwing an exception
throw new Exception();
}
}
} catch (Exception e) {
System.out.println("Exception occured");
}
}
}
If you compile and run with the above code,
10
Exception occured
While outputting the num array one by one, it is explicitly made to raise an exception when it exceeds 20. As a result, when trying to output the second 20, the processing within the catch is being executed.
The throw keyword is different from the throws keyword in that you can throw an exception anywhere.
If the Java syntax is correct, it will compile, I learned about exception handling in case the process stops during the execution of the program.
I want to be careful because there are some checked exceptions that require the description of exception handling in try-catch.
I still have only superficial knowledge, so I would like to dig deeper and understand that it can be used in practice.
Recommended Posts