[For Java beginners] About exception handling

What is an exception?

Refers to some trouble that occurs during program execution.

--Bugs created by programmers carelessly --Incorrect requirements and specifications --Inconvenience of execution machine and --Inconvenience of cooperation with other software

There are various types of software, but the software used by the user does not stop, stop working, or even if it works, it does not process normally even if a problem occurs. Do not. Therefore, programmers are required to ** "programming in case of emergency **" to deal with various situations. It can be said that this exception handling plays a role corresponding to it.

try、catch、finally

Enclose the process in which an exception may occur in a try block, and describe the process when an exception occurs in the catch block following the try block.

try Multiple statements can be written in the try block. If an exception occurs, the subsequent processing in the try block is skipped **, and control is immediately transferred to the corresponding catch block. Once control is transferred to the catch block, subsequent try block processing will not be executed regardless of necessity.

catch The catch block is a block for describing the processing when an exception occurs. ** The purpose of the catch block is to return the program to the normal state **, and when the processing of this block is completed, "the trouble has been resolved and the normal operation is restored. Since a plurality of catch blocks can be described for each type of exception that has occurred, the handling process can be changed for each type of exception.

It is also possible to omit the catch block. Omitting the catch block is a case where the method cannot determine how to handle the exception.

When preparing multiple catch blocks, ** If you write code that cannot be reached by any pattern of exception, the compiler will generate a compilation error. ** **

[Example of unreachable case]

SampleException



 public class SampleException extends Exception{}

SubSampleException



 public class SubSampleException extends SampleException{}

Main


 
 public class Main {
 	public static void main(String[] args) {
 		try {
 			sample();
 			sub();
 		} catch (SampleException e) {
 			System.out.println("A");
 		} catch (SubSampleException e) {
 			System.out.println("B");
 		}
 	}
 
 	private static void sample() throws SampleException {
 		throw new SampleException();
 	}
 
 	private static void sub() throws SubSampleException{
 	
 }

main method Call the sample () method on the first line of the try block → catch (SampleException e) {} Receives the block and performs the processing content described in the block.

Call the sub () method on the second line of the main method → ** catch (SampleException e) {} Block ** receives and performs the processing content described in the block. Before reaching SubSampleException, it is caught by the superclass SampleException.

Therefore,

[Output result] A A

This is the result.

SubSampleException is thrown by calling the sub () method on the second line of the try block, but since the SampleException class is a superclass of the SubSampleException class, it is possible to catch this exception even in the SampleException block. Therefore, processing is performed in the block received by the SampleException class written earlier before the block receiving the exception by SubSampleException.

In such a case, the catch block in SubSampleException is judged to be unreachable code, and the compiler raises a compilation error.

finally

--Network disconnection while connected --Close files that remain open --Release of database connection status while holding

Regardless of whether an exception occurs or not, the process to be executed exists regardless of the form of the program. The finally block is for describing the process you want to execute regardless of whether or not an exception has occurred.

When the finally block is described, if no exception occurs, the process described in the finally block is executed after the try block is executed. If an exception occurs, control is transferred from the try block to the catch block, and then the finally block is executed.

The finally block is for describing the process you want to execute regardless of whether an exception has occurred, and this is the same even if it is returned in the ** catch block, and return returns control to the calling method. Before, the finally block is always executed. ** **

Finally blocks do not have to be separated by exception type.

The finally block is not executed only when the System.exit method is called in the try block or catch block to kill the application, or when the JVM or OS crashes **.

About rules in writing try-catch-finally syntax

--The syntax of the try-catch-finally statement cannot change its order of appearance.

→ Therefore, the order cannot be changed like catch-try-finally and try-finally-catch.

--Nested try-cacth-finally statements can be written.

sample



public class Main {
	public static void main(String[] args) {
		try {
			try {
				String[] array = { "A", "B", "C" };
				System.out.println(array[3]); //①
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("D"); //②
			} finally {
				System.out.println("E"); //③
			}
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("F");
		} finally {
			System.out.println("G"); //④
		}
	}
}

When multiple try-catch are nested in this way, it is ** the closest catch block that corresponds to the exception that receives the thrown exception. ** **

So in the above code, (1) Since an attempt was made to output the fourth value for an array array that has only three values in the try block, control was transferred to the cacth block. (2) After processing with the nearest catch block corresponding to the exception that occurred in (1) ③ Process in the inner finally block and ④ Finally, the outer finally block processes.

It becomes the flow. At this time, the ** finally block is always executed, so both the inner and outer finally processes are executed. ** **

throw and throws

Java exception handling includes processing called "throw" and "throws". Both mean "throw" the process, but the content is very different.

throw Intentionally raise an exception to handle the exception. ** Describe in the method. ** **

example


void sample (int num) {
    if(num < 0) { 
        throw new IllegalArgumentException(“Negative values cannot be used.”);
    }
}

throws Exceptions that occur in the method are not handled in the ** own method, but are handled by the method caller. ** ** Exception handling is not described in the method in which throws is written, and exception handling is performed in the method on the side that called the method in which throws is written.

example


public static void sample() throws IOException{
	FileWriter fw = new FileWriter("data.txt");
}

FileWriter is a simple class for writing a character file, and if it is not caught by the try-catch statement, a compile error will occur ** Check exception **, so it is necessary to write a try-catch statement when processing. However, by describing throws, the method caller makes it correspond.

About checked exceptions and non-checked exceptions

There are two main types of troubles that occur during program execution in Java.

--An error that indicates that the program cannot deal with it, such as a trouble in the execution environment. --Exceptions that the program can handle

There are two.

Exceptions are further divided into checked and unchecked exceptions.

--Checked exception Exception that the compiler checks whether exception handling is described (try-catch is required) --Unchecked exception Exception that the compiler does not check whether exception handling is described (try-cacth is optional)

Java is based on checked exceptions to prevent programmers from forgetting to write exception handling. In the history of software becoming huge and complicated, the number of mistakes that programmers forget to describe exception handling has increased, and the background is that the automatic check function by the compiler was incorporated from the reflection that caused the bug. ..

Java exception classes are roughly divided

It is divided into, and represents an error, a checked exception, and an unchecked exception, respectively.

All subclasses of the Exception class are checked exceptions, except for ** RuntimeException and its subclasses. ** ** Therefore, the exception class that inherits the Exception class is forced to either try-catch or declare it in the throws clause. On the other hand, even if it is a subclass of Exception, ** RuntimeException and its subclass are treated as unchecked exceptions. ** (RuntimeException is a subclass of Exception) Therefore, RuntimeException and its subclasses are not forced to try-catch. Of course, you can write a try-catch without being forced. Also, ** unchecked exceptions do not matter if they are not declared in the throws clause. ** **

The error is represented by the Error class, but ** it is the subclass that is actually used. ** ** For example, subclasses that inherit from Error include OutOfMemoryError, NoClassDefFoundError, and StackOverflowError. In addition, in order to be classified as ** error, it is necessary to inherit Error. ** ** When these troubles occur, the JVM creates an instance of the corresponding Error subclass and notifies the program. This is the same mechanism as an exception, but in the case of an ** error, unlike an exception, you are not required to "handle it programmatically". ** Therefore, there is no need to try-catch or declare with throws. (It is only "not required" and can be caught and processed if necessary.)


――What kind of exceptions each class supports --Whether it corresponds to a checked exception or a non-checked exception

For etc.

Java SE 8 API specification https://docs.oracle.com/javase/jp/8/docs/api/ You can check the details from.

Recommended Posts

[For Java beginners] About exception handling
[Java] About try-catch exception handling
Java exception handling?
About exception handling
About exception handling
[Java] Exception handling
☾ Java / Exception handling
Java exception handling
Java exception handling
About Ruby exception handling
[Java] Practice of exception handling [Exception]
Java debug execution [for Java beginners]
[Java] Basic statement for beginners
Java exception handling usage rules
Java for beginners, data hiding
Exception handling techniques in Java
Java application for beginners: stream
[Java Silver] (Exception handling) About try-catch-finally and try-with-resource statements
[In-house study session] Java exception handling (2017/04/26)
[For beginners] About the JavaScript syntax explained by Java Gold
Exception handling
Classes and instances Java for beginners
Exception handling Exception
[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
Learn Java with "So What" [For beginners]
About the procedure for java to work
[Ruby on Rails] About bundler (for beginners)
[For beginners] Difference between Java and Kotlin
Java (exception handling, threading, collection, file IO)
try-catch-finally exception handling How to use java
About Java interface
ruby exception handling
For JAVA learning (2018-03-16-01)
[Java] About arrays
[Java] Exception instance
Something about java
Where about java
About Java features
Ruby exception handling
About Java threads
2017 IDE for Java
[Java] About interface
About Java class
About Java arrays
About java inheritance
Java for statement
About List [Java]
About java var
About Java literals
About Java commands
A story about Java 11 support for Web services
A collection of simple questions for Java beginners
[For beginners] About lambda expressions and Stream API
[Introduction to Java] Basics of java arithmetic (for beginners)
Questions in java exception handling throw and try-catch
Let's use Java New FileIO! (Introduction, for beginners)
About Java log output
About Java functional interface
[Java] for statement, while statement
Java, about 2D arrays