Java exception handling?

0. Introduction

As usual, I didn't know the Java exception, so I summarized it. This time (what?) I will write an article as a memo for myself.

1. What is exception handling?

There were various definitions of exceptions, so I quoted from Reference 1 p.264.

There are roughly two types of troubles that occur during program execution in Java. error </ font> that indicates a situation that the program cannot handle, such as a trouble in the execution environment, and exception </ font> that the program can handle There are two.

Exceptions are further divided into checked exceptions and unchecked exceptions. A checked exception </ font> is an exception that the compiler checks to see if exception handling has been written. The other unchecked exception </ font> is an exception where the compiler does not check if you have written exception handling.

And that. In short, it can be divided into three. Furthermore, there are exception classes corresponding to each exception, and their relationships are as follows.

スライド1.PNG

(I want to put a subclass as well)

2. Basics of each exception

① Inspection exception

Exception class that inherits Exception, which is a class of checked exception, must be declared in try-catch or throws clause. The inspections here are catches and throws. If you do not check for checked exceptions, you will get a compilation error.

** ② Unchecked exception **

Even in the subclass of Exception, if RuntimeException is inherited, it is treated as an unchecked exception, and processing such as try-catch becomes unnecessary. Of course, there is no problem even if exception handling is described.

** ③ Error **

Exceptions such as running out of memory or failing to read the file. Like unchecked exceptions, you don't have to handle exceptions.

3. How to write exception handling

3.1 Standard writing style

① Catch Exception When explicitly throwing an exception, add throw (check exception only? Validate) The parameter of the catch block is Throwable, so you can catch all exceptions.

try {  //Enclose the processing that may raise an exception
  throw new Exception();
} catch (Exception e) {
  ...  //Handled when an exception occurs during try
} finally {
  //Executed with or without an exception
}

(2) Use throws in the method declaration that throws an Exception.

private void hogehoge() throws Exception {
  throw new Exception();
}

3.2 Multi-catch

You can specify multiple exception classes to catch. I quoted from Reference 2.

//For Java 6 or earlier
try {
  . . . 
} catch (IOException ex) {
     logger.log(ex);
     throw ex;
} catch (SQLException ex) {
     logger.log(ex);
     throw ex;
}

//For Java 7 or later
try {
  . . . 
} catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

3.3 If you write a throw of a check exception, definitely write a catch

A method that throws a checked exception will result in a compile error unless it is caught or rethrown. .. ..

public void method() throws Exception {}

// case1
try {
  method();
} catch (Exception e) {  //Error without catch
  ...
} 

// case 2
public void method2() throws Exception {  //Error if not rethrown
  method();
}

4. Behavior after exception occurs

4.1 If an exception occurs in the for statement, no further loop processing will be performed.

Reference 1 Quoted from p.349. Since StirngIndexOutOfboundsException occurs when ʻi = 1, the loop processing of ʻi> 1 is not executed.

String[] array = {"abcde", "fgh", "ijk"};
String[] array2 = new String[3];
int i = 0;
try {
  for (String s: array) {
    array2[i] = s.substring(1, 4);
    i++;
  }
} catch (Exception e) {
  System.out.println("Error");
}

for (String s: array2) {
  System.out.println(s);
}

//Execution result
//Error Output due to catching an error
// bcd     array2[0]
// null    array2[1]
// null    array2[2]

4.2 Precautions when overriding the method throwing the exception

If you override the method that is throwing the exception, the following restrictions are added to that method (reference 3 p. 299 with some expressions changed).

(1) The exceptions that can be thrown by subclass methods are the same as the exceptions thrown by superclass methods, or the exceptions of that subclass. ② No matter what exception the superclass method throws, the subclass method can throw it as RuntimeException or an exception of that subclass (it can be defeated as a runtime exception). ③ In the first place, just because a superclass method throws an exception, it is not essential to throw it in a subclass method.

Give a concrete example (quoted from Reference 3 p.300). Here, NG: Compile error.

class Super { void method() throws IOException {} }

class SubA { void method() }  //OK You don't have to throw an exception
class SubB { void method() throws FileNotFoundException {} }  //Throwing in a subclass of OK IOException
class SubC { void method() throws Exception {} }  //Throwing in a superclass of NG IOException
class SubD { void method() throws ClassNotFoundException {} }  //Throwing in an exception class that is not inherited from NG IOException
class SubE { void method() throws RuntimeException {} }  //OK I'm defeating a run-time exception

5. Reference

    1. Sumito Shiga (2019) "Thorough capture Java SE 8 Silver problem collection [1Z0-808] correspondence" Published by Impress Co., Ltd.
  1. [In-house study session] Java exception handling (2017/04/26)
    1. Michiko Yamamoto (2015) Java Programmer Silver SE 7 (5th print issued) Published by Shoeisha Co., Ltd.

Recommended Posts