Java exception handling

Introduction

This article is a record of what I understand for those who are studying Java.

The Java functions and description methods are described in the following list. This time is exception handling.

-Variables and types, type conversion -Variable Scope ・ Character string operation (in preparation) ・ Array operation (in preparation) ・ Operator (in preparation) ・ Conditional branch (in preparation) ・ Repeat processing (in preparation) -Exception handling Current page ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation)

What is exception handling?

The idea of exception handling is to describe the response in advance in case an unexpected behavior occurs in the code and an exception occurs.

Exception is something different from error in the first place

An exception is an anomalous event during program execution. It is often mixed with an error, but it is completely different, and an error is an abnormal event that cannot be handled even on a virtual machine, and it will be forcibly terminated, so exception handling cannot handle it. The exception is that you can proceed with the program without ending the operation.

About the mechanism of exception handling

I will explain the try ~ catch statement.

class Main{
    public static void main(String args[]){
        try{
            int[] array = {0,1,2};

            System.out.println(array[3]);
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("I got an exception");
        }
    }
}

The above description is in the form of try ~ catch. As a mechanism, when the same exception as the catch class occurs in try and catch, the exception statement is passed to catch (exception statement), and the contents of catch work. It is easy to understand if you think that it is almost like this.

When you compile and run

I got an exception

Is displayed. The contents of catch are moving.

Check exception (check exception)

Checked exceptions are exception handling used for processing that does not work unless exception handling is included. I think it's hard to imagine with just these words, so I'll actually describe it.

The code below has no exception handling.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class Main{
    public static void main(String args[]){
        BufferedReader bufferReader = null;
        FileReader fileReaderr = null;

        //Input file
        fileReaderr = new FileReader("test.txt");
        bufferReader = new BufferedReader(fileReaderr);

        //Read line by line and output
        String line;
        while ((line = bufferReader.readLine()) != null) {

            System.out.println(line);

            //Intentionally close the stream and raise an IOException
            bufferReader.close();
        }
    }
}

When I try to compile this

test.java:11:error:The exception FileNotFoundException is not reported. Must be captured or declared to throw
        fileReaderr = new FileReader("test.txt");
                      ^
test.java:16:error:Exception IOException is not reported. Must be captured or declared to throw
        while ((line = bufferReader.readLine()) != null) {
                                            ^
test.java:21:error:Exception IOException is not reported. Must be captured or declared to throw
            bufferReader.close();
                              ^

It may be a little hard to see, but the above description is a nuance that says that this behavior will not work without exception handling.

IOException does not allow compilation without exception handling. So IOException is the target of checked exceptions.

So, let's enclose the part where these operations are performed with try ~ catch.


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class Main{
    public static void main(String args[]){
        BufferedReader bufferReader = null;
        FileReader fileReaderr = null;

        try {
            //Input file
            fileReaderr = new FileReader("test.txt");
            bufferReader = new BufferedReader(fileReaderr);

            //Read line by line and output
            String line;
            while ((line = bufferReader.readLine()) != null) {

                System.out.println(line);

                //Intentionally close the stream and raise an IOException
                bufferReader.close();
            }
        } catch (IOException e) {
            System.out.println("IOException occurs");
        }
    }
}

If you compile and run this

IOException occurs

By reading the txt file in the process and forcibly terminating it in while, IOException occurs in try. At that time, exception handling works and the output operation in catch is performed.

You can also eliminate compilation errors by defining throws in your method.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class Main{
    public static void main(String args[]) throws IOException{
        BufferedReader bufferReader = null;
        FileReader fileReaderr = null;

        //Input file
        fileReaderr = new FileReader("test.txt");
        bufferReader = new BufferedReader(fileReaderr);

        //Read line by line and output
        String line;
        while ((line = bufferReader.readLine()) != null) {

            System.out.println(line);

            //Intentionally close the stream and raise an IOException
            bufferReader.close();
        }
    }
}

You can compile with this description as well. Even with this description, you can follow the check exceptions. Just run

Exception in thread "main" java.io.FileNotFoundException: test.txt (No such file or directory)
	at java.base/java.io.FileInputStream.open0(Native Method)
	at java.base/java.io.FileInputStream.open(FileInputStream.java:212)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:154)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:109)
	at java.base/java.io.FileReader.<init>(FileReader.java:60)
	at Main.main(test.java:11)

An exception will occur during execution and processing will end. The difference from try ~ catch is that there is no follow (catch) when an exception occurs.

As for the processing flow, IOException was issued first for try ~ catch, and at that point, the process of the catch statement was skipped, so another exception did not occur.

Since throws are only in the state that IOException is allowed at this point, it means that another exception occurs after that and the program is terminated. Throws are described in detail in another item, so please take a look there as well.

By the way, I've heard that Java is the only concept of checked exceptions. So if you come from another language, you may be confused by the error that appears even though the process is correct.

Unchecked exception

This is a common form in other languages, and it is an arbitrary Exception that describes exception handling. This time, I will check with ArrayIndexOutOfBoundsException (accessing elements that do not exist in the array).

This is a description without exception handling.

class Main{
    public static void main(String args[]){
        int[] array = {0,1,2};

        System.out.println(array[3]);
    }
}

I'm trying to reference the third array array in the output, but I only have arrays from 0 to 2. But it doesn't cause a compile error, and when I run it

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at Main.main(test.java:6)

I got an ArrayIndexOutOfBoundsException. I was told that I was trying to look outside the range of the array.

Next time, let's put exception handling and operate it. This is the code described in the heading exception handling mechanism.

Compiles through, just like running

I got an exception

The message in the catch statement could be displayed.

Unchecked exceptions are basically avoidable errors and are not obligatory to mention. I feel that it is rather nuanced just in case.

finally I will also introduce the case of putting finally after catch.

class Main{
    public static void main(String args[]){
        try{
            int[] array = {0,1,2};

            System.out.println(array[2]);
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("I got an exception");
        }finally{
            System.out.println("Works with either");
        }
    }
}

This is a process that does not give an exception, but if you compile and execute it

2
Works with either

The processing in finally is also working like this. This time I will try it with the description that makes an exception.

class Main{
    public static void main(String args[]){
        try{
            int[] array = {0,1,2};

            System.out.println(array[3]);
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("I got an exception");
        }finally{
            System.out.println("Works with either");
        }
    }
}

When you compile and run

I got an exception
Works with either

The display looks like this. In this way, it is displayed in try regardless of the presence or absence of exceptions. In either case, the process you want to move and happen will be described here.

throw Until now, exception handling has been followed in the flow of performing this operation when an exception occurs, but you can operate exception handling yourself (in terminology, throw an exception) with a throw statement.

First, let's describe the throw.

class Main{
    public static void main(String args[]){
        System.out.println("Exception throw");
        try{
            throw new Exception("Throw an exception");
        }catch(Exception e){
            System.out.println("Exception handling");
        }
    }
}

When you run

Exception throw
Exception handling

This process is in try

throw new IOException("Throw an exception");

Is working. An Exception is issued with this description, and the catch statement supplements it, resulting in two outputs.

throws throws is a specification that the method caller performs exception handling when an exception occurs. I think it's hard to imagine with just these words, so I'll actually describe them here as well.

class Main{
    public static void main(String args[]){
        System.out.println("Exception throw");
        try{
            Main.mikan();
        }catch(Exception e){
            System.out.println("Exception handling");
        }
    }

    static void mikan() throws Exception{
        throw new Exception("Throw an exception");
    }
}

When you compile and run it

Exception throw
Exception handling

It will be displayed. As a flow of operation, the mikan method is called in the try statement of the main method.

The throws Exception is defined in the called mikan method. Simply put, if an Exception is issued inside a method, it's passed to the caller.

Since we are issuing an Exception in the method, we will throw the exception to the caller. Catch supplements it, and the output of exception handling moves.

However, in this sample, for the ease of image, Exception handling is supplemented with catch, but when actually writing it, it is better to describe the exception that may occur with this method. think. Therefore, the sample from here is described to receive IOException (check exception).

It should be noted in throws that if the method is defined to throw a checked exception, an error will occur if the caller does not enclose try ~ catch, and if throws is not defined, try ~ catch It is an error even if the caller is surrounded by. This is also actually described.

Here, the method caller is enclosed in try ~ catch, but the method side does not define throws.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class Main{
    public static void main(String args[]){
        try{
            Main.mikan();
        }catch(IOException e){
            System.out.println("I'm getting an IOException");
        }
    }

    static void mikan(){
        BufferedReader bufferReader = null;
        FileReader fileReaderr = null;
        //Input file
        fileReaderr = new FileReader("test.txt");
        bufferReader = new BufferedReader(fileReaderr);

        //Read line by line and output
        String line;
        while ((line = bufferReader.readLine()) != null) {
            System.out.println(line);

            //Intentionally close the stream and raise an IOException
            bufferReader.close();
        }
    }
}

When I try to compile this

test.java:9:error:Exception IOException is not thrown in the body of the corresponding try statement
        }catch(IOException e){
         ^
test.java:18:error:The exception FileNotFoundException is not reported. Must be captured or declared to throw
        fileReaderr = new FileReader("test.txt");
                      ^
test.java:23:error:Exception IOException is not reported. Must be captured or declared to throw
        while ((line = bufferReader.readLine()) != null) {
                                            ^
test.java:27:error:Exception IOException is not reported. Must be captured or declared to throw
            bufferReader.close();
                              ^
4 errors

An error is displayed. The bottom three errors are similar to the errors when not enclosed in try ~ catch, and are errors for the state where it seems that the correspondence of IOException is not described even though it is a checked exception.

The above error is an error saying that IOException does not occur in try ~ catch. It actually happens in the method, but since it is not declared, the try side cannot confirm it.

Next, there is no description of try ~ catch in the method caller, and in the method, let's check the operation with the person who defines throws.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class Main{
    public static void main(String args[]){
        Main.mikan();
    }

    static void mikan() throws IOException{
        BufferedReader bufferReader = null;
        FileReader fileReaderr = null;
        //Input file
        fileReaderr = new FileReader("test.txt");
        bufferReader = new BufferedReader(fileReaderr);

        //Read line by line and output
        String line;
        while ((line = bufferReader.readLine()) != null) {
            System.out.println(line);

            //Intentionally close the stream and raise an IOException
            bufferReader.close();
        }
    }
}

This code is a copy of the process that must be enclosed in try in the sample check exception to the mikan method. When I try to compile this

Exception IOException is not reported. Must be captured or declared to throw
        Main.mikan();
                  ^

I get an error. This is the opposite of the previous one, and it is known from the throws definition that an IOException will occur on the caller side, but it is an error that it must be enclosed in try ~ catch because it is a checked exception.

Enclose the above sample in a try statement.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class Main{
    public static void main(String args[]){
        try{
            Main.mikan();
        }catch(IOException e){
            System.out.println("I'm getting an IOException");
        }
    }

    static void mikan() throws IOException{
        BufferedReader bufferReader = null;
        FileReader fileReaderr = null;
        //Input file
        fileReaderr = new FileReader("test.txt");
        bufferReader = new BufferedReader(fileReaderr);

        //Read line by line and output
        String line;
        while ((line = bufferReader.readLine()) != null) {
            System.out.println(line);

            //Intentionally close the stream and raise an IOException
            bufferReader.close();
        }
    }
}

Now when you compile and run

I'm getting an IOException

It will be displayed. An exception has occurred in the mikan method, and the caller has been able to catch and process the output in the catch statement. If there are checked exceptions defined in throws, pay attention to the caller's description.

At the end

I have described various exceptions. As I mentioned a little above, if you are studying Java, you can handle errors by checking the checked exceptions.

Recommended Posts

[Java] Exception handling
☾ Java / Exception handling
Java exception handling
Java exception handling
Exception handling Exception
[Java] Practice of exception handling [Exception]
[Java] About try-catch exception handling
Java exception handling usage rules
Exception handling techniques in Java
About exception handling
About exception handling
ruby exception handling
[In-house study session] Java exception handling (2017/04/26)
[Java] Exception instance
Ruby exception handling
Step-by-step understanding of Java exception handling
[For Java beginners] About exception handling
Java (exception handling, threading, collection, file IO)
try-catch-finally exception handling How to use java
About Ruby exception handling
Exception handling practice (ArithmeticException)
[Ruby] Exception handling basics
[java] throw an exception
Spring Boot exception handling
Questions in java exception handling throw and try-catch
Classes that require exception handling
Java basic learning content 7 (exception)
Java's first exception handling (memories)
exception
Java
Java
Handling of time zones using Java
[Rails] How to write exception handling?
[Note] Handling of Java decimal point
Unexpected exception when using Java DateTimeFormatter
[Java] What is Concurrent Modification Exception?
Exception handling with a fluid interface
[Java] Exception types and basic processing
(Learning memo) Java 2nd grade measures: Q4 main points (exception handling)
[Introduction to Java] About exception handling (try-catch-finally, checked exception, unchecked exception, throws, throw)
Leverage Either for individual exception handling in the Java Stream API
Java learning (0)
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
java (constructor)
Java array
java (override)
java (method)
Java Day 2018
Java string
Java static
Java serialization