Home  >  Article  >  Java  >  How to catch exceptions in Java

How to catch exceptions in Java

王林
王林forward
2023-05-10 17:07:063284browse

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");
    }
}

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子句进行资源关闭
}

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!

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