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

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

问题描述




  1. 首先,检查异常应该在编译期间查找异常。不同来源提供的示例引用数据库连接,文件处理作为其中一些,而 unchecked 异常应该在程序员的一部分上寻找错误,如索引超出范围数组等。

不是这样吗?我的意思是,数据库连接是在运行时完成的,对吧?文件处理也是如此。您在编译期间不打开文件句柄,那么为什么在编译期间可能会出现可能的错误?另一方面,将数组索引到其范围之外已经在程序中完成,可以在编译期间进行检查(如果异常索引在运行时由用户提供,则可以将其作为运行时)问题)。我在这里缺少什么?



2其次,如何 RunTimeException ,本身是未选中,子类异常,这是检查?这是什么意思?



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

  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(输入一个字母);
}
catch(java.io.IOException exc){
System.out.println(I / O exception occurred。);
ch ='X';
}
System.out.println(你按+ ch);
}
}

throws 这里需要吗?为什么我不能通常使用 try-catch 语句这样(抱歉,我不知道如何模拟一个 IO Exception ,所以不能自己检查!):

  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(输入一个字母);
}
catch(java.io.IOException exc){
System.out.println(I / O exception occurred。);
ch ='X';
}
System.out.println(你按+ ch);
}
}


解决方案

CheckedException需要由调用者处理,未检查的异常不会。



所以,当你设计你的应用程序时,你应该考虑到你正在管理什么样的异常情况。



例如,如果您设计了一种检查某些用户输入的有效性的验证方法,那么您知道调用者必须检查验证异常并将错误显示给用户在一个很好看的方式。这应该是一个检查的例外。



或者,对于可以恢复的特殊情况:想象一下你有一个负载均衡器,你想通知呼叫者 n服务器已关闭,因此呼叫方必须恢复事件,将消息重新路由到另一个服务器;这应该是一个检查的异常,因为调用者(客户端)尝试恢复错误至关重要,不要让错误中断程序流。



<相反,有许多条件不应该发生,和/或应该打破程序。例如,编程错误(如除零,空指针异常),API(IllegalStateException,OperationNotSupportedException)的错误使用,硬件崩溃或仅可恢复的一些次要情况(与服务器的连接丢失),或者末日:-);在这种情况下,正常的处理是让异常到达您的代码的最外部块,向用户显示发生不可预测的错误,并且应用程序无法继续执行任何操作。这是一个致命的条件,所以您唯一可以做的是将其打印到日志中或在用户界面中向用户显示。在这些情况下,捕获异常是错误的,因为在捕获异常之后,需要手动停止程序以避免进一步的损坏;所以可能会更好的让某种异常击中风扇:)



由于这些原因,还有一些异常在JRE中也被取消:OutOfMemoryError(不可恢复),NullPointerException(这是一个需要修复的错误),ArrayIndexOutOfBoundsException(另一个错误示例)等。



我个人认为也应该取消选中SQLException ,因为它表示程序中的错误或数据库的连接问题。但是有很多例子,你得到异常,你真的没有任何线索如何管理(RemoteException)。



处理异常的最好方法是:if您可以恢复或管理异常,处理它。否则让异常传出;有人会需要处理。如果你是最后一个别人,你不知道如何处理异常,只需显示它(记录或显示在用户界面中)。


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

  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 Secondly, how can RunTimeException, itself being unchecked, subclass Exception, which is checked? What does this signify?

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

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 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.

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.

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" :)

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.

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).

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天全站免登陆