How does Java know RuntimeExceptions are not flagged?

How does the Java compiler know that java.lang.RuntimeException

its subclasses are java.lang.Exception

unchecked as well, as they inherit from , which is a checked exception? I have looked at the code and there seems to be not something inside the class that tells the compiler this.

+3


source to share


2 answers


Since it is defined this way in language spec # 11.1.1 :

  • Unmanaged exception classes are runtime exception classes and error classes.
  • Checked exception classes are all exception classes other than unchecked exception classes. That is, the checked exception classes are all subclasses of Throwable other than RuntimeException and its subclasses, and Error and its subclasses.


Thus, it is not part of the code of the various exception classes, it is only a language-specific convention that compilers must follow in order to be compatible.

+8


source


It is enough that it expands RuntimeException

. At compile time, it knows what a class hierarchy is, so if it includes RuntimeException

it is not set. Otherwise, it will be checked. Remember checked / unchecked is a compiler limitation, not a runtime limitation, there are ways to make Java throw checked exceptions that never get caught. For example using Proxy

:

public class ExceptionalInvocationHandler implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        throw new IOException("Take that, checked exceptions!");
    }
}

      

And the interface:



public interface Example {
    public void doSomething();
}

      

And create a proxy server and name it:

 Example ex = (Example) Proxy.newProxyInstance(Example.class.getClassLoader(),
     new Class[] { Example.class },
     new ExceptionalInvocationHandler());
 ex.doSomething(); // Throws IOException even though it not declared.

      

+1


source







All Articles