Home > Java > javaTutorial > body text

How to catch exceptions in Java

王林
Release: 2023-05-10 17:07:06
forward
3317 people have browsed it

1. try...catch...finally

Put the possible exceptions in the try code block, followed by catch to handle the corresponding exception, a try can have multiple catch clauses (no subclass relationships can exist) to catch different exceptions.

public static void main(String[] args){
    try{
        // 这是可能出现异常的代码块
        int sum = 0;
    }
    catch(Exception err){
        // 对对应异常进行处理
        System.out.println(err.getMessage());
    }
    finally {
        // 一般执行关闭流的操作
        System.out.println("do the close operate");
    }
}
Copy after login

2. try-with-resource

After the try code block is finished running, the resource will be automatically closed, and there can also be catch and finally clauses, these clauses will be executed after the resource is closed.

public static void main(String[] args){
    // 把需要打开的流资源写在try后的括号中
    try(var in = new Scanner(new FileInputStream("I:/javastudy/demo.txt"), StandardCharsets.UTF_8)){
        while(in.hasNext()){
            System.out.println(in.next());
        }
    }
    // 作异常处理 此时流资源已关闭
    catch (Exception err){
        System.out.println(err.getMessage());
    }
    // 无需使用finally子句进行资源关闭
}
Copy after login

The above is the detailed content of How to catch exceptions in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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