简体   繁体   English

Java中的已检查和未检查的异常,这些断言是真的吗?

[英]Checked and unchecked exception in Java, are these assertions true?

I have some doubts about the difference between checked exception and unchecked exception . 我对已检查的异常未经 检查的异常之间的区别存有疑问。

I know that checked exception typically represent invalid conditions in areas outside the immediate control of the program such as invalid user input, database problems, network outages, absent files, etc. 我知道检查异常通常表示程序直接控制之外的区域中的无效条件,例如无效的用户输入,数据库问题,网络中断,缺少文件等。

I also know that checked exception are subclass of Exception abstract class and that a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow). 我还知道, checked异常Exception抽象类的子类,并且一个方法必须为其实现抛出的所有已检查异常建立一个策略 (要么将已检查的异常传递到堆栈中,要么以某种方式处理它)。

So, in practice, what exactly means this last assertion? 那么,在实践中,究竟是什么意味着最后的断言呢?

Can I simply say that checked exceptions are checked at compile-time. 我可以简单地说在编译时检查已检查的异常 It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. 这意味着如果一个方法抛出一个已检查的异常,那么它应该使用try-catch块处理异常,或者它应该使用throws关键字声明异常,否则程序将给出一个编译错误。 It is named as checked exception because these exceptions are checked at Compile time. 它被命名为已检查异常,因为在编译时检查这些异常。

So, if a method throws a checked exception I can handle it in 2 differents way: 因此,如果一个方法抛出一个已检查的异常,我可以用两种不同的方式处理它:

  1. I have to handle it into a try-catch block, something like this: 我必须把它处理成一个try-catch块,如下所示:

     try{ //statements that may cause an exception } catch (exception(type) e(object))‏ { //error handling code } 
  2. Using the throws keyword used in method declaration, in order to explicitly specify the exceptions that a particular method might throw. 使用方法声明中使用的throws关键字,以便显式指定特定方法可能抛出的异常。 When a method declaration has one or more exceptions defined using throws clause then the method-call must handle all the defined exceptions. 当方法声明使用throws子句定义了一个或多个异常时,方法调用必须处理所有已定义的异常。

    So, correct me if I am sayng a wrong assertion, the throws keyword is used to throw the retrieved checked exception to the upper level in the stack (into the caller) . 所以,如果我说错了断言,请纠正我, throws关键字用于将检索到的已检查异常抛出到堆栈的上层(进入调用者) So if a method call another method that throw a checked excepion, if it is thrown the caller method have to handle it (for example by a try catch block). 因此,如果一个方法调用另一个抛出一个检查过的异常的方法,如果它被抛出,则调用方法必须处理它(例如通过try catch块)。 Is it this reasoning correct? 这个推理是否正确?

    So is it true that checked exceptions have the disadvantage that introduce a form of tight-coupling because if I have a chain of methods and the last one throws a checked exception or I handle it into the code of its father or all the intermediate methods must declare the exception by the throws keyword on the method declaration? 因此, 检查异常具有引入紧耦合形式的缺点是正确的,因为如果我有一个方法链并且最后一个抛出一个已检查的异常,或者我将其处理到其父代码或所有中间方法必须通过方法声明中的throws关键字声明异常? Is this assertion correct? 这个断言是否正确?

At the contrary the unchecked exception are not checked at compile time. 相反,在编译时不检查未经检查的异常 It means if your program is throwing an unchecked exception and even if you didn't handle/declare that exception, the program won't give a compilation error. 这意味着如果您的程序抛出未经检查的异常,即使您没有处理/声明该异常,程序也不会给出编译错误。 Most of the times these exception occurs due to the bad data provided by user during the user-program interaction. 大多数情况下,由于用户在用户程序交互期间提供的错误数据而发生这些异常。 It is up to the programmer to judge the conditions in advance, that can cause such exceptions and handle them appropriately. 程序员可以提前判断条件,这可能导致这些异常并适当地处理它们。 All Unchecked exceptions are direct sub classes of RuntimeException class. 所有未经检查的异常都是RuntimeException类的直接子类。

For example I can have a situation like this: 例如,我可以有这样的情况:

class Example {  
   public static void main(String args[])
   {
    int num1=10;
    int num2=0;
    /*Since I'm dividing an integer with 0
     * it should throw ArithmeticException*/
    int res=num1/num2;
    System.out.println(res);
   }
}

Compiling this class the compiler give me no error but running it I will obtain an ArithmeticException tath is an unchecked exception because it happens at runtime. 编译这个类编译器没有给我任何错误,但是运行它我将获得一个ArithmeticException tath是一个未经检查的异常,因为它发生在运行时。

So I think that it is the developer that have to handle this case doing something like: 所以我认为开发人员必须处理这种情况,例如:

class Example {  
   public static void main(String args[])
   {
    int num1=10;
    int num2=0;
    /*Since I'm dividing an integer with 0
     * it should throw ArithmeticException*/
    try {
        int res=num1/num2;
    } catch(ArithmeticException e) {
         System.out.println("Division for 0, this is not a good idea !!!");
    }

    System.out.println(res);
   }
}

So my doubts are: 所以我的怀疑是:

  1. It seems to me that I can use the try catch block also for the unchecked exception . 在我看来,我也可以使用try catch块来处理未经检查的异常 So what is the difference in the use of try catch block that exist between checked exception and unchecked exception ? 那么在已检查的异常未经 检查的异常之间存在的try catch块的使用有何不同? Is it only that with checked exception I have to use it (or use the throws keyword on the method declaration) otherwise I will obtain a compile time error message? 是否仅使用已检查的异常我必须使用它(或在方法声明中使用throws关键字)否则我将获得编译时错误消息?

  2. Also the unchecked exception are automatically propagated to the superior level into the stack of the methods call? 此外, 未经检查的异常会自动传播到上级进入方法调用的堆栈中吗?

Tnx TNX

In regard to the coupling introduced by the throws , you are absolutely right: exceptions declared in the throws clause become part of a method's public interface (in general sense of the word; without regard to Java's interfaces and public access). 关于throws引入的耦合,你是绝对正确的: throws子句中声明的throws成为方法的公共接口的一部分 (通常意义上的单词;不考虑Java的接口和公共访问)。 However, this coupling is not different from that introduced by declaring a return type or parameter types of a method. 但是,这种耦合与通过声明返回类型或方法的参数类型引入的耦合没有什么不同。 You can think of it as a third attribute of method's signature. 您可以将其视为方法签名的第三个属性。

It seems to me that I can use the try catch block also for the unchecked exception. 在我看来,我也可以使用try catch块来处理未经检查的异常。 So what is the difference in the use of try catch block that exist between checked exception and unchecked exception? 那么在已检查的异常和未经检查的异常之间存在的try catch块的使用有何不同?

You can certainly catch unchecked exceptions, but you should do it at the very top level of your program in order to prevent complete crashes. 您当然可以捕获未经检查的异常,但您应该在程序的最顶层执行此操作以防止完全崩溃。 Unchecked exceptions represent programming errors, so you cannot handle them in a meaningful way. 未经检查的异常表示编程错误,因此您无法以有意义的方式处理它们。 The best you can do is to log them, and move on. 你能做的最好的就是记录它们,继续前进。

Also the unchecked exception are automatically propagated to the superior level into the stack of the methods call? 此外,未经检查的异常会自动传播到上级进入方法调用的堆栈中吗?

Yes, they do so in the same way the checked exceptions do when an exception is declared in the throws clause and not caught. 是的,它们以与在throws子句中声明异常但未捕获的异常相同的方式执行此操作。

  1. Yes. 是。 You can use try catch block to catch unchecked exceptions as well as checked exceptions. 您可以使用try catch块来捕获未经检查的异常以及检查异常。

  2. All exceptions, whether checked or unchecked are propagated up to the next level if not caught. 所有例外情况,无论是已选中还是未选中,如果未被捕获,都会传播到下一级别。

The difference is that if a method can throw a checked exception E (either because it calls a method that throws E or because it directly throws it itself with the statement throw E ) the method declaration must include this information using throws E . 不同之处在于,如果一个方法可以抛出一个已检查的异常E (因为它调用一个throws E的方法,或者因为它直接用throw E抛出它自己抛出它),方法声明必须使用throws E包含这个信息。

Therefore if you want to call a method that can throw the checked exception E you must either put the method call in a try block or declare throws E . 因此,如果要调用可以抛出已检查异常E的方法,则必须将方法调用放在try块中或声明throws E These things are optional for unchecked exceptions. 对于未经检查的异常,这些是可选的。

Most of the time you should not catch an unchecked exception. 大多数情况下,您不应该捕获未经检查的异常。

  1. There are no differences between try catch of unchecked and checked exceptions. try catch of unchecked和checked例外没有区别。 As you told. 正如你所说。

    -If a method uses another method that may throw a checked exception, one of the two following things should be true: The method should be enclosed within a try-catch block or The method should specify this exception to be thrown in its method signature. - 如果方法使用另一个可能抛出已检查异常的方法,则下列两项内容之一应该为真:该方法应该包含在try-catch块中,或者该方法应指定在其方法签名中抛出此异常。

    -A unchecked exception may not be a part of the method signature, even if a method may throw it. - 未经检查的异常可能不是方法签名的一部分,即使方法可能抛出它。

  2. When a piece of code hits an obstacle in the form of an exceptional condition, it creates an objects of class java.lang.Throwable. 当一段代码以异常条件的形式遇到障碍时,它会创建类java.lang.Throwable的对象。 Checked and Unchecked Exceptions propagates through method calls because both are subclass java.lang.Throwable. Checked和Unchecked Exceptions通过方法调用传播,因为它们都是子类java.lang.Throwable。

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

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