Good day. There is an example:

public class Application { public static void main(String[] args) throws Exception { g(); } public static void g() throws Error { } } 

Please tell me why this code is compiled? I read Horstmann and see: "The compiler strictly follows the throws specifiers. Calling a method that generates a controlled exception, you must either process it yourself, or delegate processing to another method." It turns out that it is not necessary to handle all uncontrolled exceptions from the Error and RuntimeException classes? And we also have a main method that throws a controlled exception:

 public static void main(String[] args) throws Exception 

Is it not necessary to process it somewhere? I read and do not understand how to interpret the meaning correctly. Please tell us how to act in this example and in general.

    1 answer 1

    Please tell me why this code is compiled?

    Why shouldn't he?

    JLS §11.2:

    The unchecked exception classes are exempted from compile-time checking

    There are no exceptions, because they can be exceeded.

    .

    It turns out that it is not necessary to handle all uncontrolled exceptions from the Error and RuntimeException classes?

    Therefore, they are called "unchecked".

    Is it not necessary to process it somewhere?

    The exceptions thrown up by the main method will be handled by the virtual machine. Well, how to handle ... Displays stacktrace in stderr and terminates.

    • that's just what i wanted to know, it turns out that by throwing exceptions in the main method the program will simply complete the execution Where can I read about this nuance? - Drylozav
    • Here it is: JLS §11.3 Run Time ling encountered Run - Nofate
    • Tell me, if we threw out the throws Error exception and didn’t handle it, then the exception should be handled in its calling method, that is, main. But it turns out that the Error and Exception exceptions are different exceptions from different classes. How can the g () method with the exception Error be handled by the main method with the exception Exception? - Drylozav
    • You just send me to read JLS, which is very difficult for me now. I don’t really understand Russian, and therefore I don’t use a foreign source. These are obvious things for you, but for me this is still a deaf forest, and seeing such an obvious example for me, I try to understand all the subtleties. - Drylozav
    • Ok, pryatnenko. In general, JLS tells us that it is blocking on checks for unchecked exceptions when compiling. That is, what you specified in the signature of the throws Error method is equivalent to the absence of the corresponding instruction. --- Look at it this way: The g() method can throw an Error . Ok, push it into the main method. Those. In the main method, an Error exception will occur. Is this a checked exception? Not. Well, it means the compiler and nothing to worry about. After all, Error and so you can happen at any time. - Nofate