1

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?

MRM
  • 165
  • 6
  • Yes you can, a common usage will be to throw an `IllegalStateException` and use tryCatch to use another type of exception like `NullPointerException`, or use tryCatch to catch an exception that the user has nothing to do with, like initializing an instance of `java.awt.Robot`. – picky potato Jun 07 '21 at 06:46
  • No, you do not need any `throws` statments since no checked exception is actually thrown out of any method. – luk2302 Jun 07 '21 at 07:22
  • Added your example to the duplink to directly address this question. – Stephen C Aug 28 '22 at 03:03

1 Answers1

2

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()
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • 1
    Actually I'm throwing an exception from t() method. could you please tell me whether can I use throws and try-catch in the same method? – MRM Jun 07 '21 at 07:02
  • 4
    No you are not. You are throwing it from a `try` block and it is getting caught. There is not need to declare it as throwing . – Scary Wombat Jun 07 '21 at 07:04