About exception handling

What is an exception?

Exceptions are objects that notify you that something unexpected has happened in your program and that processing cannot continue. Exceptions make your code easier to read because you can separate the normal processing of your code from the above processing to some extent.

Difference between error and exception

Trouble during Java execution can be divided into two types: error and exception.

error Situations that cannot be dealt with by the program, such as problems in the execution environment. The program cannot continue and will be killed.

exception A situation that can be dealt with by the program. Unlike errors, you can continue your program without terminating its operation.

Check exception

When writing a method, it is a checked exception that gets angry if you do not write exception handling, and a checked exception is basically an exception that cannot be avoided even if you write the correct program. For example, the file you want to refer to is corrupted, or a DB failure occurs. Checked exceptions are exception handling that the compiler checks, and targets Execution and its subclasses.

Unchecked (checked) exception

This is an exception in which the compiler does not check whether exception handling has been written. Unchecked exceptions are arbitrarily written by the programmer and are intended for the RuntimeExcepiton class and its subclasses. Unchecked exceptions are basically avoidable errors and are not mandatory.

main.java


public static void main (String[] args) {

      int[] ary = {1, 2, 3};
    
      System.out.println(ary[3]);
}

The code above requests that the fourth be displayed even though there are only three elements in the array ary. When executed, it will be as follows.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

I got a message that I was trying to look outside the range of the array.

Let's add exception handling to this and execute it.

main.java


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

            System.out.println(ary[3]);
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("The exception");
        }
    }
}

Execution result

Exception

Exception handling ran.

try ~ catch ~ finally statement

sample.java


class Sample {
    public static void main (String[] args) {
        int ary[] = {1, 2, 3};

        System.out.println("start");

            try{
                for (int i = 0; i < 4; i++){
                    System.out.println(n[i]);
                }
            }
            catch(ArrayIndexOutOfBoundsException e){
                System.out.println("Beyond the range of the array");
            }
            finally{
                System.out.println("Output array");
            }

            System.out.println("End processing");
        }
}

Describe the process that may cause an exception in the try part, and write the process when an exception occurs in the catch part. You can also separate catch blocks according to the type of exception. Describes the last process to be executed in the finaly part.

throw and throws

throw In addition to the exception handling by try ~ catch, there is also an exception handling called throw that allows you to raise an exception yourself.

sample.java



    void test (int num) { 
        if(num == 0) { 
            throw new IllegalArgumentException("Illegal argument"); 
        }
    }

In the test method, even though a numeric type called num is specified as an argument, it is written to process when num is 0 in if minutes.

When executed, it will be as follows.

throw new IllegalArgumentException(“The argument is invalid”);

throws The name is similar to throw, but the processing is different. throws can be called to the caller when you want the exception to be handled by the caller instead of inside the method.

sample.java


import java.io.FileNotFoundException;
import java.io.FileReader;
 
class Sample {
    public static void main (String[] args) {
        System.out.println("Exception throw");
 
        try {
            methodA(); 
        } catch(FileNotFoundException e) {
            System.err.println(e.getMessage());
        } 
    }
 
    void methodA() throws FileNotFoundException {
        FileReader aFile = new FileReader("aFile.txt");
    }
}

Execution result

aFile.txt (No such file or directory)
Processing is finished

Recommended Posts

About exception handling
About exception handling
About Ruby exception handling
Exception handling
Exception handling Exception
[Java] About try-catch exception handling
Java exception handling?
ruby exception handling
Ruby exception handling
[Java] Exception handling
☾ Java / Exception handling
Java exception handling
Java exception handling
[For Java beginners] About exception handling
Exception handling practice (ArithmeticException)
Spring Boot exception handling
About the handling of Null
Classes that require exception handling
Java's first exception handling (memories)
[Java] Practice of exception handling [Exception]
[Ruby] Exception handling in functions
exception
Java exception handling usage rules
About =
[Java Silver] (Exception handling) About try-catch-finally and try-with-resource statements
Exception handling techniques in Java
[In-house study session] Java exception handling (2017/04/26)
About error handling of comment function
[Rails] How to write exception handling?
Exception handling with a fluid interface
Step-by-step understanding of Java exception handling
[Introduction to Java] About exception handling (try-catch-finally, checked exception, unchecked exception, throws, throw)
About method.invoke
About attr_accessor
About Hinemos
About inheritance
About Docker
About Rails 6
About Spring ③
[Ruby] Exception handling, give back if given
About enum
About polymorphism
About Optional
About hashes
About JitPack
About this ()
About encapsulation
About JAVA_HOME
About static
About exceptions
Self-made Exception
Java (exception handling, threading, collection, file IO)
About scope
[Maven] About Maven
try-catch-finally exception handling How to use java
Points to worry about when handling variables personally
I want to design a structured exception handling
Questions in java exception handling throw and try-catch