Why are Runtime Exceptions “unchecked” in Java?

2019-02-13 21:52发布

问题:

Why does it make sense to have Runtime Exceptions UnChecked (as opposed to if they were Checked)?

回答1:

If you didn't you would have to have try/catch blocks every time you accessed an array element, did a division operation and many other common scenarios.

To put it another way, imagine this code:

Map map = ...
int i = ...
(int[])map.get("foo")[3] = 2334 / i;

would have to check for ClassCastException, ArrayIndexOutofBoundsException, ArithmeticException, UnsupportedOperationException and NullPointerException just off the top of my head.

With Java the issue isn't unchecked exceptions. Checked exceptions are a highly controversial subject. Some say this was largely an experiment with Java and in practice they don't work but you will find plenty of people who argue they are good.

No one is arguing unchecked exceptions are bad however.



回答2:

The idea of the two kinds of exceptions in Java (checked and unchecked) is that checked exceptions should be used for error conditions that can reasonably be expected to happen, and unchecked exceptions should be used for unexpected error conditions.

For example if a file isn't found, you get a FileNotFoundException, and it's reasonable to expect your program to be able to handle such a condition. Unchecked exceptions should be used only for problems that shouldn't happen, and that really mean that there is a bug in the program if such a problem happens. For example, a NullPointerException means that your program is trying to dereference a variable that is null and that's most likely a bug.

The Java compiler forces the programmer to handle checked exceptions. This makes the programming language safer - it means that the programmer is forced to think about error conditions, which should make the program more robust.

The compiler doesn't check unchecked exceptions, because unchecked exceptions aren't supposed to happen anyway and if they do, there's nothing that the program could reasonably do at runtime; the programmer must solve the bug.

There has been some criticism to this feature in Java, some people even call checked exceptions a failed experiment and some people propose to remove checked exceptions from Java.



回答3:

This simply means that the compiler will not force you to look for an exception, but you can still throw it at runtime. As one benefit, this allows you to throw new exceptions from your classes without requiring you to alter your interface, causing callers to change their code.