[Java] Exception handling

What is exception handling?

try ... catch syntax

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class TryBasic {

  public static void main(String[] args) {
    try {
      var in = new FileInputStream("C:/data/nothing.gif");
      var data = -1;
      while ((data = in.read()) != -1) {
        System.out.printf("%02X ", data);
      }
    //Throw a FileNotFoundException exception in the FileInputStream class
    } catch (FileNotFoundException e) {
      System.out.println("The file was not found.");
    } catch (IOException e) {
      //Access the exception object through the specified exception variable (e)
      e.printStackTrace();
    }
  }
}

Stack trace

finally block

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class TryFinally {

  public static void main(String[] args) {
    FileInputStream in = null;
    try {
      in = new FileInputStream("C:/data/nothing.gif");
      var data = -1;
      while ((data = in.read()) != -1) {
        System.out.printf("%02X ", data);
      }
    } catch (FileNotFoundException e) {
      System.out.println("The file was not found.");
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //File close with or without exception
      try {
        if (in != null) {
          in.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

try-with-resource syntax

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class TryWithResources {

//Resource declaration at the beginning of the block
  public static void main(String[] args) {
    try (var in = new FileInputStream("C:/data/hogee.gif")) {
      var data = -1;
      while ((data = in.read()) != -1) {
        System.out.printf("%02X ", data);
      }
    //Automatic resource release when exiting the try block
    } catch (FileNotFoundException e) {
      System.out.println("File not found.");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Hierarchical structure of exception classes

Exception handling notes

//Multi catch
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class TryMulti {

  public static void main(String[] args) {
    try {
      var in = new FileInputStream("C:/data/nasi.gif");
      var data = -1;
      while ((data = in.read()) != -1) {
        System.out.printf("%02X ", data);
      }
      var uri = new URI( "https://www.neko.example.com");
      System.out.println(uri.toString());
    //Multi catch
    } catch (IOException | URISyntaxException e) {
      System.out.println("The file cannot be accessed.");
      e.printStackTrace();
    }
  }
}

Throw an exception

public FileInputStream(File file) throws FileNotFoundException{
//Abbreviation

Exception throw attention

public class AssertBasic {
  private static double getTrapezoidArea(double upper, double lower, double height) {
    //Exception occurs when argument is 0 or less
    assert upper > 0 && lower > 0 && height > 0;
    return (upper + lower) * height / 2;
  }
  public static void main(String[] args) {
    System.out.println(AssertBasic.getTrapezoidArea(-2, 4, 0));
  }
}

Exception rethrow

public class TryRethrow {
//MySampleException,Rethrow method may occur in MyLibException
  public static void rethrow(boolean flag) throws MySampleException, MyLibException {
    try {
      if (flag) {
        throw new MySampleException();
      } else {
        throw new MyLibException();
      }
    //Received as Exception type and thrown again as it is
    } catch (Exception e) {
      throw e;
    }
  }
}

Translation exception


import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Paths;

//You only need to be aware of MySampleException as a translation exception
public class UseTrans {
  public void readHttpPages() throws MySampleException {
    try (var reader = Files.newBufferedReader(Paths.get("C:/data/link.txt"))) {
      var line = "";
      while ((line = reader.readLine()) != null) {
        var client = HttpClient.newHttpClient();
        var req = HttpRequest.newBuilder().uri(URI.create(line)).build();
        var res = client.send(req, HttpResponse.BodyHandlers.ofString());
        System.out.println(res.body());
      }
    } catch (IOException | InterruptedException e) {
      throw new MySampleException(e);
    }
  }
}

Proprietary exception class

//Inherit Exception (derived class)
public class MySampleException extends Exception {
  //Override constructor
  public MySampleException() {
    super();
  }
  public MySampleException(String message) {
    super(message);
  }
  public MySampleException(String message, Throwable cause) {
    super(message, cause);
  }
  public MySampleException(Throwable cause) {
    super(cause);
  }
}

Recommended Posts

Java exception handling?
[Java] Exception handling
☾ Java / Exception handling
Java exception handling
Java exception handling
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
[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
Java basic learning content 7 (exception)
[Ruby] Exception handling in functions
exception
Java
[Java Silver] (Exception handling) About try-catch-finally and try-with-resource statements
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
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] ArrayDeque
java (override)
java (method)
Java Day 2018
Java string
java (array)
Java static