Search code examples
javaexceptiontry-catchthrowsillegalaccessexception

Usage of throws and try-catch in the same method


Can we use throws and try-catch in the same method?

public class Main
{
static void t() throws IllegalAccessException {
    try{
    throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
    System.out.println(e);
}
    
}
    public static void main(String[] args){
        t();
        System.out.println("hello");
    }
}

The error displayed is

Main.java:21: error: unreported exception IllegalAccessException; must be caught or declared to be thrown
        t();
         ^
1 error

So I thought of modifying the code and I added an another throws statement to main() method and the rest is same.

public class Main
{static void t() throws IllegalAccessException {
    try{
    throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
    System.out.println(e);
}
    
}
    public static void main(String[] args) throws  IllegalAccessException{
        t();
        System.out.println("hello");
    }
}

But now I'm getting the desired output. But I have some questions...

Can we use throws and try-catch in single method?

In my case is it necessary to add two throws statement , if not tell me the appropriate place to add?


Solution

  • In your code

     void t() throws IllegalAccessException
    

    you are telling the compiler that this code throws an exception (whether it does or not is another matter), and so any method calling this method either has to catch it or declare that it also throws it etc. etc.

    As you are not actually throwing an exception from t you can remove the declaration.

    void t()