Home > Java > JavaBase > body text

Examples of how to handle exceptions in java

王林
Release: 2019-11-30 15:15:44
forward
2372 people have browsed it

Examples of how to handle exceptions in java

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:

Examples of how to handle exceptions in java

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:

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template