Java 中的已检查异常与未检查异常 [英] Checked vs Unchecked Exceptions in Java

查看:21
本文介绍了Java 中的已检查异常与未检查异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解 Java 中 checkedunchecked 异常之间的区别时遇到了一些问题.

I am having some problems with understanding the differences between checked and unchecked exceptions in Java.

  1. 首先,checked 异常应该在编译时寻找异常.不同来源提供的示例引用了数据库连接、文件处理作为其中的一些,而 unchecked 异常应该寻找程序员方面的错误,例如超出数组范围的索引等.
  1. Firstly, checked exceptions are supposed to look for abnormalities during compile time. Examples provided in different sources cite database connectivity, file handling as some of them, while unchecked exceptions are supposed to look for errors on the programmer's part, like indexing beyond the range of an array, etc.

不应该反过来吗?我的意思是,数据库连接是在运行时完成的,对吧?文件处理也是如此.您不会在编译期间打开文件句柄,那么为什么在编译期间寻找可能的错误呢?另一方面,超出范围的数组的索引已经在程序中完成,可以在编译时检查(如果异常索引是用户在运行时提供的,那么它可以是运行时问题).我在这里错过了什么?

Shouldn't it be the other way round? I mean, database connectivity is done during run-time, right? Same goes for file-handling. You don't open a file-handle during compile time, so why a possible error on that is looked for during compile-time? On the other hand, indexing an array beyond its range is already done in the program, which can be checked during compile time (if the abnormal index is supplied by user during run-time, then it's okay for it to be a run-time problem). What am I missing here?

2 其次,RunTimeException,本身是unchecked,如何子类Exception,也就是checked?这意味着什么?

2 Secondly, how can RunTimeException, itself being unchecked, subclass Exception, which is checked? What does this signify?

我在 Herbert Schildt 的书中找到了一个例子,解释了 checked 异常的用法:

I found an example in Herbert Schildt's book explaining the usage of checked exceptions:

class ThrowsDemo {
   public static char prompt(String str)
      throws java.io.IOException {
  System.out.print(str + ": ");
  return (char) System.in.read();
  }
  public static void main(String args[]) {
    char ch;
    try {
      ch = prompt("Enter a letter");
    }
    catch(java.io.IOException exc) {
     System.out.println("I/O exception occurred.");
     ch = 'X';
    }
    System.out.println("You pressed " + ch);
    }
}

这里是否需要 throws 子句?为什么我不能正常使用像这样的 try-catch 语句(对不起,我不知道如何模拟 IO Exception,所以无法检查我自己!):

Is the throws clause necessary here? Why can't I do it just normally with a try-catch statement like this (sorry I don't know how to simulate an IO Exception, so couldn't check it myself!):

class ThrowsDemo {
   public static char prompt(String str)  {
     System.out.print(str + ": ");
     return (char) System.in.read();
  }
  public static void main(String args[]) {
    char ch;
    try {
      ch = prompt("Enter a letter");
    }
    catch(java.io.IOException exc) {
     System.out.println("I/O exception occurred.");
     ch = 'X';
    }
    System.out.println("You pressed " + ch);
    }
}

推荐答案

CheckedException 需要调用者处理,Unchecked 异常不需要.

CheckedException needs to be handled by the caller, Unchecked exception don't.

因此,当您设计应用程序时,您应该考虑到您正在处理什么样的异常情况.

So, when you design your application you should take in mind what kind of exceptional situation you are managing.

例如,如果您设计了一个验证方法来检查某些用户输入的有效性,那么您知道调用者必须检查验证异常并以美观的方式向用户显示错误.这应该是一个检查异常.

For example, if you design a validation method that checks the validity of some user input, then you know that the caller must check the validation exception and display the errors to the user in a nice looking way. This should be a checked exception.

或者,对于那些可以恢复的异常情况:假设您有一个负载平衡器,并且您想通知调用者n"台服务器之一已关闭,因此调用者必须恢复事件,将消息重新路由到另一台服务器;这应该是一个检查异常,因为调用者(客户端)尝试恢复错误至关重要,不要让错误破坏程序流程.

Or, for those exceptional conditions that can be recovered: imagine you have a load balancer and you want notify the caller that one of the "n" servers is down, so the caller must recover the incident re-routing the message to another server; this should be a checked exception, because it is crucial that the caller (client) tries to recover the error, and don't just let the error to break the program flow.

相反,有许多情况不应该发生,和/或应该破坏程序.例如,编程错误(如除以零、空指针异常)、错误使用 API(IllegalStateException、OperationNotSupportedException)、硬件崩溃或一些不可恢复的小情况(与服务器的连接丢失),或世界末日:-);在这些情况下,正常的处理是让异常到达代码的最外层,向用户显示发生了不可预知的错误并且应用程序无法继续执行.这是一种致命的情况,因此您唯一能做的就是将其打印到日志中或在用户界面中将其显示给用户.在这种情况下,捕获异常是错误的,因为捕获异常后需要手动停止程序,以免造成更大的损失;所以最好让某种异常打击粉丝":)

Instead, there are many conditions that should not happen, and/or should instead break the program. For example, a programming error (like division by zero, null pointer exception), a wrong usage of an API (IllegalStateException, OperationNotSupportedException), an hardware crash, or just some minor situation that are not recoverable (lost connection to a server), or a doomsday :-) ; in those cases, the normal handling is to let the exception reach the most outer block of your code that displays to the user that an unpredictable error has occurred and the application can't do nothing to continue. It's a a fatal condition, so the only thing you can do is to print it to the logs or showing it to the user in the user interface. In those cases, catching the exception is wrong, because, after catching the exception you need to manually stop the program to avoid further damages; so it could be better to let some kind of exception "hit the fan" :)

由于这些原因,JRE 中也有一些未检查的异常:OutOfMemoryError(不可恢复)、NullPointerException(这是一个需要修复的错误)、ArrayIndexOutOfBoundsException(另一个错误示例)等等.

For those reasons there are some exceptions that are Unchecked also in the JRE: OutOfMemoryError (unrecoverable), NullPointerException (it's a bug that needs to be fixed), ArrayIndexOutOfBoundsException (another bug example), and so on.

我个人认为 SQLException 也应该不选中,因为它表示程序中的错误,或者与数据库的连接问题.但是有很多例子你会遇到你真的不知道如何管理的异常 (RemoteException).

I personally think that also SQLException should be unchecked, since it denotes a bug in the program, or a connection problem to the database. But there are many examples where you get exception that you really don't have any clue in how to manage (RemoteException).

处理异常的最佳方法是:如果您可以恢复或管理异常,请处理它.否则让异常过去;其他人将需要处理.如果您是最后一个其他人"并且您不知道如何处理异常,只需将其显示(记录或显示在 UI 中).

The best way to handle exceptions are: if you can recover or manage the exception, handle it. Otherwise let the exception pass out; somebody else will need to handle. If you are the last "somebody else" and you don't know how to handle an exception, just display it (log or display in the UI).

这篇关于Java 中的已检查异常与未检查异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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