Home>Article>Java> Examples of how to handle exceptions in java

Examples of how to handle exceptions in java

王林
王林 forward
2019-11-30 15:15:44 2296browse

Examples of how to handle exceptions in java

First of all, there are two main ways to handle exceptions: one istry catch, and the other isthrows.

1. Put code that may cause exceptions in try catch

try{}. Put in catch{} the processing after catching the exception. Among them, the function ofe.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 addfinally. Regardless of whether the exception in the try block is caught or not, the finally block will be executed at the end, unless there issystem.exit(( 0)(system.exit(0) is used to exit the virtual machine).

Online learning video sharing:java online tutorial

2. Throw and throws

throwIt 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:

Examples of how to handle exceptions in java

throwsis 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:

Examples of how to handle exceptions in java

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete