How can I tell if an exception is being checked or compile-time checking?

I looked at the class RuntTimeException

and didn't check it at compile time. Why is the class not checked

at compile time and checked

at run time?

https://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html

               | Throwable |
               +-----------+
                /         \
               /           \
      +-------+          +-----------+
      | Error |          | Exception |
      +-------+          +-----------+
       /  |  \           / |        \
     \________/        \______/      \
      unchecked                   checked
                +------------------+
                | RuntimeException |
                +------------------+
                  /   |    |      \
                \_________________/

                   unchecked

      

  • RuntimeException

    class extends class Exception

    and is still unchecked? How?.
  • How does the compiler decide whether to check this class at runtime

    or in compile

    time ?.
+3


source to share


3 answers


RuntimeException class extends exception class and still not installed? How?.

It's a design choice. The Java language designers decided that RuntimeException and Error, and the classes that extend them, are by definition unchecked exceptions. So this is just a rule of the tongue.



How does the compiler decide whether this class should be checked at runtime or compile time?

The compiler checks the type of the thrown exception. If it is a RuntimeException or an error, the exception is not checked.

+1


source


The class is unchecked, you are talking about exceptions here. The exception is whether compile time checked or not. A checked exception must be caught or declared in the signature of the method in which it can be thrown. An unchecked exception requires no special treatment.



+1


source


The rules are as follows:

  • All exception classes that extend RuntimeException

    (including RuntimeException

    ) are unchecked exceptions.
  • All other classes that extend Exception

    are checked exceptions - excluding RuntimeException

    and anything below that.
  • Error

    and everything below this is also not noted.

"Checked" means that the Java compiler checks to see if your code is handling the exception by catching it, or if the method in which the exception might be thrown has a clause throws

indicating that the method can throw that type of exception.

See "Catch or Specify a Requirement" in the Oracle Java Tutorials which explain this in detail.

The answer to both questions is that it works like this because it is specified in the Java Language Specification.

+1


source







All Articles