Are multiple outliers an exception or runtime?

I have an exception chain in which method1throws an exception on method2, which throws an exception on main. For some reason, the compiler makes me have to deal with an error method2and marks it as an error, if I do not do it, indicating that it checked exception. But when the same one is Exceptionthrown further to the line main, the compiler allows me to ignore it and not display any errors.

The original exception to method1is ParseExceptionthat is being checked. But the method has a common sentence throws Exceptionin the header, and the same object is passed to method2, which has an identical sentence throws Exception. When and how does this exception lose the check / catch status of the compiler?

Edited to clarify:

public void method1() throws Exception{
   // code that may generate ParseException
}

public void method2() throws Exception{
   method1(); //compiler error (if the throws clause is left out)
}

public static void main(String[] args){
   method2(); //ignored by compiler, even though the exception isn't caught or thrown or handled at all
}

Edit: Sorry everyone, the question was based on an error ... The main method actually had a sentence throws Exceptionthat I was missing. I deleted this and the code now behaves as expected. Thanks for the help!

+3
source share
4 answers

, : a RuntimeException , ; . ( , RuntimeException Exception โ€” Java, .)

, . , ( ). throws Exception, Exception , throws Exception. throws โ€” , throws Exception, throws ParseException.

( " ( )", , , , , , , throws. )

, , : 1. , 2. main , Exception.

, () , main throws Exception:

public class CheckTest
{
    public static final void main(String[] params)
    {
        new CheckTest().method2();
    }

    public void method1() throws Exception{
        throw new java.text.ParseException("foo", 2);
    }

    public void method2() throws Exception{
        this.method1();
    }
}

:

CheckTest.java:27: unreported exception java.lang.Exception; must be caught or declared to be thrown

                new CheckTest().method2();
                                       ^
1 error
+6

. , unchecked, - RuntimeException .

+3

Exception . throw Exception ( ), , Exception, .

. OP, . main Exception, .

+2

Is it possible that your compiler does not complain about the problem in main(), because it encounters the problem in method2()and stops checking the syntax at this point? Both should be a mistake. Have you fixed the call in method2()and got a clean compilation?

0
source

Source: https://habr.com/ru/post/1744357/


All Articles