[Java] Exception types and basic processing

Exception types and correspondence

The ** exception class ** provided by the API is in the following inheritance hierarchy.

Here, we will deal with exceptions especially for Exception-type exceptions.

Basic support with try-catch

Exception handling can be described in the try-catch statement.

try{
    FileWriter fw = new FileWriter("c:¥¥data.txt");
    fw.write("hellow!");
}catch(IOException e){
    System.exit();
}

If you do not handle exceptions, the following compilation error will occur in the Exception system.

Exception java.io.IOException is not reported.
You must catch or declare a throw to throw.

(I haven't read it yet) Enclose the relevant part with try-catch or Declare throw IOException in the method definition and The caller is required to handle exceptions.

Catch abstractly

If you write the conditional part of catch like ʻException e`, Catch Exception-type exceptions or RuntimeException-type exceptions. The intention is to roughly catch the offspring class of the Exception class.

try{
    FileWriter fw = new FileWriter("c:¥¥data.txt");
    fw.write("hellow!");
}catch(Exception e){
     System.out.println("Something went wrong"); //Somehow ...
}

I don't know if the phrase "catch abstractly" is correct ...

finally attached

If you add finally after catch, You can set the process you want to execute regardless of the occurrence of an exception. For cleaning up, such as closing open files and closing database and network connections.

try{
    FileWriter fw = new FileWriter("c:¥¥data.txt");
    fw.write("hellow!");
}catch(IOException e){
    System.out.println("Something went wrong");
}finally{
    fw.close();
}

Automatically close ()

If writing the finally block is a hassle, write () in the first try.

try(
    FileWriter fw = new FileWriter("c:¥¥data.txt");
){
    fw.write("hellow!");
}catch(IOException e){
    System.out.println("Something went wrong");
}

If you go with this, it seems that the first opened data.txt will be automaticallyclosed (). However, it is limited to types that implement the java.lang.AutoCloseable interface.

throws declaration

When declaring with a method, write as follows.

** ... method name throws exception class 1, exception class 2, ... **

Sub.java


public class Sub{
    public static void subsub() throws IOException{
         FileWriter fw = new FileWriter("date.txt");
         fw.write("hello!");
    }
}

Main.java


public class Main{
    public static void main(Strgin[] args){
        try{
            //There are various processes ...
            subsub();
        }catch(IOException e){
            System.exit();
        }
    }
}

Because it is not processed by the called subsub method It feels like processing with the main method of the caller.

throws are also used to throw exceptions.

Throw an exception

Write as follows. Note that it is singular.

** throw exception instance; **

Or

** throw exception instance ("error message"); **

Person.java


Public class Person{
    int age;
    public class setAge(int Age){
        if(age <= 0){
        //If it is 0 or less
            throw new IllgalArgumentExeception("The age should be a positive number. Specified value=" + age);
        }
        //If it is a positive number
        this.age = age;
    }
}

Main.java


public class Main{
    public static void main(String[] args){
        Person p = new Person();
        p.setAge(-128); //Now try to set the wrong value.
    }
}

As an execution result,

Exception in thread "main" java.lang.IllegalArgumentException:The age should be a positive number. Specified value=-128
  at Person.setAge(Person.java:6)
  at Main.main(Main.java:4)

The throws statement throws an IllegalArgumentException instance to the JVM and reports it. The exception is thrown to the main method, but here the JVM eventually kills the program because it hasn't caught the exception.

Definition of original exception class

You can create your own exception class by inheriting the existing exception class. The method of making is the same as the general inheritance method.

For example, when developing a program to read documents or something I want exception handling when reading an unsupported document file ...

UnsupportedDocumentFileException.java


public class UnsupportedDocumentFileException extends Exception{
    public UnsupportedDocumentFileException(String){
        //Constructor that receives an error message
        super(msg);
    }
}

Main.java


public class Main{
    public static void main(String[] args){
        try{
            //Throwing an exception on a trial basis... 
            throw new UnsupportedDocumentFileException
                ("This is an unsupported document file");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

ʻException.printStackTrace () `outputs the following information.

--Class name of the exception thrown --Explanation of the exception passed in the constructor --Caller method and file name / line number

Convenient.

Reference book

[Introduction to Java 2nd Edition] (https://www.amazon.co.jp/%E3%82%B9%E3%83%83%E3%82%AD%E3%83%AA%E3%82%8F%E3%81%8B%E3%82%8BJava%E5%85%A5%E9%96%80-%E7%AC%AC2%E7%89%88-%E3%82%B9%E3%83%83%E3%82%AD%E3%83%AA%E3%82%B7%E3%83%AA%E3%83%BC%E3%82%BA-%E4%B8%AD%E5%B1%B1-%E6%B8%85%E5%96%AC/dp/484433638X) Pp.562-595

Recommended Posts

[Java] Exception types and basic processing
[Java] Basic types and instruction notes
Basic data types and reference types (Java)
Java basic data types and reference types
Java basic data types
About Java basic data types and reference type memory
Java variable declaration, initialization, and types
Java Primer Series (Variables and Types)
[Java] Loop processing and multiplication table
Reading and writing Java basic files
Basic processing flow of java Stream
[Note] Cooperation between Java and DB (basic)
[Introduction to Java] Variable declarations and types
Java exception handling?
Java basic grammar
Java basic grammar
[Java] Exception instance
Java basic knowledge 1
Java thread processing
[Java] Basic structure
[Java] [Basic] Glossary
Java string processing
Java basic grammar
Java and JavaScript
XXE and Java
Java basic grammar
[Java] Exception handling
☾ Java / Exception handling
Java exception handling
[Java] Multi-thread processing
Java exception handling
Java exercises [Basic]
[Java] Stream processing
java iterative processing
[Java] Personal summary of classes and methods (basic)
About Java data types (especially primitive types) and literals
[Processing x Java] Data type and object-oriented programming
Questions in java exception handling throw and try-catch
Getters and setters (Java)
[Java] Types of comments and how to write them
[Java] Thread and Runnable
Java true and false
[java] throw an exception
java basic knowledge memo
Link Processing and SQLite
[Java] String comparison and && and ||
[Java] Data type ①-Basic type
Java basic date manipulation
Java review ① (development steps, basic grammar, variables, data types)
Java basic naming conventions
Java learning memo (basic)
Java --Serialization and Deserialization
[Java] Arguments and parameters
I summarized the types and basics of Java exceptions
timedatectl and Java TimeZone
JAVA constructor call processing
[Java] Branch and repeat
[Java] Main data types
[Java Silver] (Exception handling) About try-catch-finally and try-with-resource statements
Java random, various processing
Equivalence comparison of Java wrapper classes and primitive types