First of all, there are two main ways to handle exceptions: one is try catch
, and the other is throws
.
1. Put code that may cause exceptions in try catch
try{}. Put in catch{} the processing after catching the exception. Among them, the function of e.printStackTrace()
in catch is to print the location and reason of the program error on the console. Only when an exception occurs in the code in the try block will it go to the catch block.
Some exception captures will add finally
. Regardless of whether the exception in the try block is caught or not, the finally block will be executed at the end, unless there is system.exit(( 0)
(system.exit(0) is used to exit the virtual machine).
Online learning video sharing: java online tutorial
2. Throw and throws
throw
It is a statement that throws an exception. It appears inside the function and is used to throw a specific exception instance. The statement after throw is executed has no effect and is transferred directly to the exception handling stage.
Examples are as follows:
throws
is a function method that throws exceptions. It is usually written in the head of the method to throw Some exceptions are not resolved by themselves, but are thrown to the caller of the method for resolution (try catch
).
Examples are as follows:
If you want to know more related articles, you can visit: Getting Started with Java
The above is the detailed content of Examples of how to handle exceptions in java. For more information, please follow other related articles on the PHP Chinese website!