简体   繁体   English

Java中的异常抛出顺序

[英]Order of throws exceptions in Java

I am writing code for reading files into Java. 我正在编写用于将文件读入Java的代码。

I have a main method that throws three Exceptions. 我有一个抛出三个异常的主要方法。 I am wondering what would the impact would be if I switched the order of writing the exceptions in the same line of public static void main(String[] args) . 我想知道如果在public static void main(String[] args)的同一行中切换写异常的顺序会产生什么影响。

public class SwitchTester {

    private static Scanner pathInput;

    public static void main(String[] args) throws IOException, NoSuchElementException, IllegalStateException{

I use the code inside the main method. 我在main方法中使用代码。 The order of exceptions I use is IOException, NoSuchElementException, IllegalStateException in this code. 在此代码中,我使用的异常顺序为IOException,NoSuchElementException,IllegalStateException。 Would it matter to keep the same order in the main line? 在主线上保持相同的顺序是否重要? Would it matter to keep throws in the main line or not at all? 将罚球保持在主线上是否重要?

    try{         
        pathInput = new Scanner(path);
    }catch(IOException ioException){
        System.err.println("Error opening file. Terminating.");
        System.exit(1);
    }

    System.out.printf("%-10s%-15s%-15s%10s%n", "Port", "Destination",
             "Source", "Data-type");

    //readRecords
    try{
        while(pathInput.hasNext()){ //while there is more to read, display record contents
            System.out.printf("%-10s%-15s%-15s%10s%n", pathInput.next(), 
                    pathInput.next(), pathInput.next(), pathInput.next());
        }
     }catch(NoSuchElementException elementException){
         System.err.println("File improperly formed. Terminating.");
     }catch(IllegalStateException stateException){
         System.err.println("Error reading from file. Terminating.");
     }

I would appreciate your answer! 谢谢您的回答! Thanks! 谢谢!

The order in which the exceptions is listed in the throws clause of the method declaration totally doesn't matter. 方法声明的throws子句中列出的异常顺序完全无关紧要。 It definitely does not have to have any relation to where you throw the exceptions in the code. 绝对不必与在代码中引发异常的位置有任何关系。

Assuming this is a main method called only from the JVM, and none of your code is actually calling this method, this is one time where it would be perfectly fine to save yourself some typing and write throws Exception . 假设这是仅从JVM调用的主要方法,并且您的代码实际上都没有调用此方法,那么这是一次可以很好地保存自己的类型并编写throws Exception (On the other hand if you refactor the main method so that it calls separate methods that handle different functions then you would want those methods to be more descriptive of what checked exceptions they throw.) (另一方面,如果您重构main方法,以便它调用处理不同功能的单独方法,那么您希望这些方法更能描述它们抛出的检查异常。)

The order of exceptions in your throws clause has no functional impact on calling code. throws子句中的异常顺序对调用代码没有功能性影响。 Nor does omitting unchecked throwables (those that derive from Error or RuntimeException ). 也不会省略未经检查的可抛出对象(那些由ErrorRuntimeException派生的对象)。 You are however required to declared any checked exceptions; 但是,您必须声明任何已检查的异常; they are not optional. 它们不是可选的。

JLS 8.4.6 documents the requirements for the throws clause: JLS 8.4.6记录了throws子句的要求:

It is permitted but not required to mention unchecked exception classes ( §11.1.1 ) in a throws clause. 允许但不要求在throws子句中提及未经检查的异常类(第11.1.1节 )。

In general, what you want to be careful about is whether you want to declare a superclass in the throws clause, or discrete subclasses. 通常,要注意的是要在throws子句中声明超类还是在离散子类中声明。 For example, it is generally bad practice to say throws Exception instead of eg throws FileNotFoundException because it puts a higher burden on callers that want to handle thrown exceptions intelligently. 例如,说throws Exception而不是throws FileNotFoundException通常是一个坏习惯,因为它给希望智能处理抛出异常的调用者增加了负担。

When you catching the exceptions you should always catch the most specific first and then the most generic ,but if you are throwing the exceptions type, you do not need to catch them. 捕获异常时,应始终首先捕获最specific的异常,然后捕获最generic的异常,但是如果抛出异常类型,则无需捕获它们。

For more info of exception takea look at hierarchy-of-exception and this package-tree 有关异常的更多信息,请查看异常层次结构和此包树

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM