java的未检查异常有哪些,检查与Java中的未检查异常

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值