最新消息:

java免检异常(包含RuntimeException)与必检异常的区别

JAVA 大步 3687浏览 0评论
java异常类之间的继承关系:
java_exception_class
RuntimeException、Error以及它们的子类都被称为免检异常(unchecked Exception)。所有其他异常都称为必检异常(checked Exception),意思是指编译器会强制程序员检查并处理它们(如果没有throws或try-catch语句来处理必检异常,ide会报错,编译器无法编译代码)。而对于免检异常,既可以不处理异常,也可以处理异常。
 
验证如下:
MyException : 必检异常
MyRuntimeException : 免检异常
 
下面代码使用免检异常:
上面的代码可以正常的抛出我们自定义的运行时异常(免检异常),我们这里没有使用throws和try-catch来处理免检异常。
 
 
 
 
 
使用必检异常,如下:

 可以看到,当我们没有使用throws或try-catch来处理异常的时候,就会ide会抛出错误,而代码也无法编译通过。
修改,添加处理异常的语句:
 
 
如何决定到底使用免检异常还是必检异常,取决于你是否想要客户端去处理异常情况,当用户处理了异常,则程序还是可以正常的运行,这时候就需要使用必检异常,比如,参数传入为null的情况。
输出:
可以看到,即使是在调用showName方法后遇到了异常,后面的"System.out.println("end"); " 语句依然执行了,说明在处理了错误异常的情况下,程序没有中断。
如果需要用户直接终止程序,则使用免检异常,如连接数据库等,这种就无需用户处理了,直接抛出异常,终止程序,如果一个web程序连数据库都连不上,肯定没有运行的必要了。
输出:
 可以看到,调用showName方法遇到异常后, 后面的"System.out.println("end"); " 语句就不会再执行了,整个程序终止了。
 
 
通过上面的例子,可以明白免检异常和必检异常的区别了。
下面的内容可以加深理解:
 
 
Checked vs. unchecked exceptions

There are two kinds of exceptions in Java, checked and unchecked, and only checked exceptions need appear in throws clauses. The general rule is: Any checked exceptions that may be thrown in a method must either be caught or declared in the method's throws clause. Checked exceptions are so called because both the Java compiler and the Java virtual machine check to make sure this rule is obeyed.

Whether or not an exception is "checked" is determined by its position in the hierarchy of throwable classes. Figure 4 shows that some parts of the Throwable family tree contain checked exceptions while other parts contain unchecked exceptions. To create a new checked exception, you simply extend another checked exception. All throwables that are subclasses of Exception, but not subclasses of RuntimeException are checked exceptions.

Figure 4. Checked and unchecked throwables

The conceptual difference between checked and unchecked exceptions is that checked exceptions signal abnormal conditions that you want client programmers to deal with. For instance, because the drinkCoffee() method allocates memory with the new operator, it could potentially complete abruptly by throwing an OutOfMemoryError. This is not a checked exception, because it's not a subclass of Exception. It's a subclass of Error. Conceptually, OutOfMemoryError isn't a checked exception because you don't want client programmers to have to deal directly with the fact that drinkCoffee() could complete abruptly due to low memory.

When you place an exception in a throws clause, it forces client programmers who invoke your method to deal with the exception, either by catching it or by declaring it in their own throws clause. If they don't deal with the exception in one of these two ways, their classes won't compile. For example, because the drinkCoffee() method declares three exceptions in its throws clause, the serveCustomer() method, which invokes drinkCoffee(), has to deal with those three exceptions. In this case, serveCustomer() catches one exception, TooColdException, but not the other two. If serveCustomer() hadn't declared in its throws clause the other two exceptions, TemperatureException and UnusualTasteException, the VirtualCafe class would not have compiled.

Most unchecked throwables declared in java.lang (subclasses of Error and RuntimeException) are problems that would be detected by the Java virtual machine. Errors usually signal abnormal conditions that you wouldn't want a program to handle. Problems with linking, such as NoClassDefFoundError, or memory, such as StackOverflowError, could happen just about anywhere in a program. In the rare cases in which they happen, it is usually reasonable that the thread terminate.

Although most runtime exceptions (members of the RuntimeException family) also are thrown by the Java virtual machine itself, they usually are more an indication of software bugs. Problems with arrays, such as ArrayIndexOutOfBoundsException, or passed parameters, such as IllegalArgumentException, also could happen just about anywhere in a program. When exceptions like these are thrown, you'll want to fix the bugs that caused them to be thrown. You won't, however, want to force client programmers to wrap every invocation of a method that uses arrays with a catch clause for ArrayIndexOutOfBoundsException.

You can throw and catch unchecked exceptions just like checked exceptions, but the Java Language Specification advises against throwing errors. It is intended that errors be thrown only by the Java runtime. You may, however, reasonably throw runtime exceptions. You can throw a runtime exception declared in java.lang or declare your own subclasses of RuntimeException.

To decide whether to throw a checked exception or an unchecked runtime exception, you must look at the abnormal condition you are signalling. If you are throwing an exception to indicate an improper use of your class, you are signalling a software bug. The class of exception you throw probably should descend from RuntimeException, which will make it unchecked. Otherwise, if you are throwing an exception to indicate not a software bug but an abnormal condition that client programmers should deal with every time they use your method, your exception should be checked.

 

 

转载请注明:大步's Blog » java免检异常(包含RuntimeException)与必检异常的区别

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
SiteMap