Get started with java-10.2 exception parameters and capture exceptions
In this section, we will briefly discuss the exception parameters and capture exceptions.
1. Exception Parameters
You can add parameters to the exception to make the exception clearer.
Package com. ray. ch10; public class Test {public static void main (String [] args) {throw new RuntimeException (runtime exception );}}
Output:
Exception in thread main java. lang. RuntimeException: A running Exception occurs.
At com. ray. ch10.Test. main (Test. java: 7)
As you can see from the output, we can pass some information to the programmer through parameters to make the code exception clearer.
2. Capture exceptions
(1) try Block
package com.ray.ch10;public class Test {public static void main(String[] args) {try {//dosomething} finally {}}}
Note: try block must be used together with finally. In fact, this ensures that even if there is an exception, there will be final processing.
Try only tries various statements. If there is an exception, the code will be stopped at the exception point, and finally ends, but the exception will not be handled in this process. (Of course we can also regard finally as a kind of processing)
package com.ray.ch10;public class Test {public static void main(String[] args) {try {throw new RuntimeException();} finally {System.out.println(dosomething);}}}
(2) try catch
Package com. ray. ch10; public class Test {public static void main (String [] args) {try {throw new RuntimeException (throwing a runtime exception);} catch (RuntimeException e) {System. out. println (exception during processing); e. printStackTrace ();} catch (Exception e) {System. out. println (Exception Handling); e. printStackTrace ();}}}
Output:
Handling runtime exceptions
Java. lang. RuntimeException: a runtime exception is thrown.
At com. ray. ch10.Test. main (Test. java: 7)
The output result shows the steps to handle exceptions:
(1) Exceptions discovered
(2) locate the exception of your own type. Generally, the exception type is already an exception information.
(3) Handling exceptions
(4) throw an exception and disconnects code execution from the exception location
Note: Generally, you need to find your own type of exception first. If you cannot find the exception, you can then perform an upward transformation.
3. Exception Handling Model
Exception Handling models can be divided into two types: disconnection and recovery.
The above demonstrates a disconnected processing model. If it is a Restoration Model, place try in while until the processing result is satisfactory, but this adds numerous maintenance costs, therefore, in most cases, only the disconnected model is used.
Summary: This section briefly describes the exception parameters and capture exceptions.