简体   繁体   中英

How to write unchecked exception in java?

Is that possible to write unchecked exception in Java? Maybe would it be good idea to tell compiler don't check the throws while compiling?

How does JVM differ checked vs unchecked exception? Is it JVM or Java Class level?

Unchecked exceptions are mainly compiler-level, as they internally get thrown around in the same way. Only differences are requirements of them being explicit in code and method signatures.

You create an unchecked exception by inheriting from RuntimeException as opposed to Exception .

JLS 11.2 states :

The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor (§8.4.6, §8.8.5). This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled. For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).

....

The unchecked exception classes (§11.1.1) are exempted from compile-time checking.

Any exception that extends RuntimeException is an unchecked exception. You can write your own the same way (by extending RuntimeException that is).

您只需要扩展java.lang.RuntimeException

It's pretty easy. All unchecked exceptions are subclasses of RuntimeException. Just make your exception class inherit from RuntimeException, and you should be good to go.

您必须编写具有扩展RuntimeException类的类与编写检查的异常类似,但是我们需要扩展RuntimeException类

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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