[Java Silver] (Exception handling) About try-catch-finally and try-with-resource statements

try-catch-finally and try-with-resource statements

Both are syntaxes for describing exception handling.

** * What is exception handling **

Java exceptions include Error, Exception (checked exception), and RuntimeException (unchecked exception).

-** Error ** is a problem that cannot be dealt with by the program (*** Unlike compilation error **, ** Exception **) -Exception (check exception) ** is a problem that a compile error occurs if the processing when an exception occurs is not described. - RuntimeException (unchecked exception) ** is an exception that can be handled arbitrarily when an exception occurs. Since it is a subclass of Exception, if you write a catch block that catches Exception first and then write a catch block that catches RuntimeException, it will be unreachable code and a compile error will occur.

Make the method ignore the exception ・ Raise an exception from the method

-** throws **: When the corresponding exception occurs in the method, the process of throwing the exception to the called side instead of catching in the method of confidence. ** Methods that throw checked exceptions ** must declare the possibility of throwing in ** throws. ** **

Example)

public test() throws IndexOutOfBounsException {
   //processing
}

→ Even if IndexOutOfBounsException occurs in the process, the test method is ignored. IndexOutOfBoundsException occurs on the side that executed the test method.

-** throw **: Raise an exception from the method Example)

public test(){
  throw new IndexOutOfWxception();
}

→ When executing the test method, an IndexOutOfWxception exception is thrown in the test method.

try-catch-finally statement

-Try block: Processing that may cause an exception -Catch block: Processing when an exception occurs -Finally block: The last process to be executed in any case

** [Example of try-catch-finally statement] **

public class Main {
	public static void main(String[] args){
     System.out.println(test(null));  

    //Finally block processing
    //Argument is null

   //Is displayed

     System.out.println(test(10));

  //The value of the argument is 10
  //Finally block processing
  //The argument was valid

   //Is displayed

  }

    public static String test(Object obj){
        try{
            System.out.println("The value of the argument is" + obj.toString());
        }catch(NullPointerException e){
            return "Argument is null";
        }finally{
            System.out.println("Finally block processing");
        }
        return "The argument was valid";
    }
}

try-with-resource statement

** Syntax to release a resource ** by automatically calling the resource's ** close method ** when an exception occurs

**-Process execution order ** ① Release the resource with the close method (2) Exception handling of catch block ③ Finally process the block

** * Release resources before exception handling **

** [Example of try-with-resource statement] ** (From Java Silver Kuromoto)

public class Main {
	public static void main(String[] args){
     try(Sample s = new Sample()){
         throw new Exception();  //Raise an Exception
     }catch(Exception e){
         System.out.println("A");
     }finally{
         System.out.println("B");
     }
  }
}

class Sample implements AutoCloseable{
    public void close() throws Exception{
        System.out.println("C");  //C is displayed when the close method is executed
    }
}

↓ "C A B" is displayed. Because it is executed in the order of close method → catch block → fianlly block

reference) Official document / AutoCloseable interface

An object that can hold resources (such as files and socket handles) until it is closed. The close () method of an AutoCloseable object is automatically called at the end of the try-with-resources block in which the object is declared in the resource specification header. This build ensures immediate release and avoids resource shortage exceptions and errors that may occur otherwise.

Recommended Posts

[Java Silver] (Exception handling) About try-catch-finally and try-with-resource statements
[Java] About try-catch exception handling
[For Java beginners] About exception handling
About exception handling
About exception handling
[Java] Exception handling
☾ Java / Exception handling
Java exception handling
Java exception handling
[Introduction to Java] About exception handling (try-catch-finally, checked exception, unchecked exception, throws, throw)
try-catch-finally exception handling How to use java
Questions in java exception handling throw and try-catch
About Ruby exception handling
[Java Silver] About initialization
About inheritance (Java Silver)
[Java] Practice of exception handling [Exception]
About Java variable declaration statements
Java if and switch statements
Java exception handling usage rules
[Java Silver] About equals method
[Java] About String and StringBuilder
About Java Packages and imports
Exception handling techniques in Java
Java while and for statements
About Java static and non-static methods
About fastqc of Biocontainers and Java
[In-house study session] Java exception handling (2017/04/26)
[Java beginner] About abstraction and interface
About Java primitive types and reference types
Step-by-step understanding of Java exception handling
This and that about Base64 (Java)
[Java] Exception types and basic processing
Java Silver exam procedure and learning method
[About JDBC that connects Java and SQL]
Java (exception handling, threading, collection, file IO)
Exception handling Exception
[ev3 × Java] Interface, implementation and inheritance (event handling)
About Java data types (especially primitive types) and literals
Error logging and exception handling that you can't often see in the Java area