在方法中分配throws子句 [英] Assigning throws clause in method

查看:42
本文介绍了在方法中分配throws子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在主方法签名中使用 throws 子句来处理异常,如以下示例所示?

How can I use the throws clause in the main method signature to handle an exception, as shown in the following example?

import java.io.File;
import java.io.IOException;

public class Exception {

    public static void main(String ... args) throws IOException {
        ioExceptionTest();
    }

    public static void ioExceptionTest() throws IOException {
        File file = new File("C:\\Users\\User\\Desktop\\Test.txt");

        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }
}

对我来说这没有意义.

推荐答案

如果方法使用 throws 子句作为方法签名,则该方法中引发的任何异常都将引发给调用方,该方法被调用.调用者可以选择使用try catch块来处理异常,也可以使用throws子句将异常引发给调用它的人.

If a method uses a throws clause it the method signature, then any exceptions raised in that method will be raised to the caller where the method was called. The caller can either choose to handle the exception with a try catch block, or use a throws clause to raise the exception to whoever called it.

main方法上的throws子句意味着将向 Java虚拟机

A throws clause on the main method means the exception will be raised to the Java Virtual Machine, which will handle the exception, and print the stack trace.

class Example {
    // handle exception with a try catch block
    public static void main(String ... args) {
        try {
            myMethod();
        } catch (Exception e) {
            // handle the exception
        }
    }

    // raise exception to the Java Virtual Machine
    public static void main(String ... args) throws Exception {
            myMethod();
    }

    static void myMethod() throws Exception {
        // do something which may throw an Exception, such as
        throw new Exception("Meaningful description");
    }
}

这篇关于在方法中分配throws子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆