0

if without the throws IllegalArgumentException, I can still throw exception that catched by the catch block in the main fucntion, why I need throws IllegalArgumentException??

public class ExceptionsTest {
    public static void funcThrowsException(int n) throws IllegalArgumentException{
        if(n == 0){
            throw new IllegalArgumentException("ex");
        }
    }

    public static void main(String[] args) {
        try{
            funcThrowsException(0);
        }catch (IllegalArgumentException e){
            System.out.println(e.getMessage());
        }

    }
}
public class ExceptionsTest {
    public static void funcThrowsException(int n){
        if(n == 0){
            throw new IllegalArgumentException("ex");
        }
    }

    public static void main(String[] args) {
        try{
            funcThrowsException(0);
        }catch (IllegalArgumentException e){
            System.out.println(e.getMessage());
        }

    }
}

Their output are same:

ex

Process finished with exit code 0

I don't know why we need throws keywords

miao sun
  • 3
  • 2
  • 1
    depending on the type of Exception, throws is (or isn't) mandatory. IllegalArgumentException is a subclass of RuntimeException, and for RuntimeException, it is not required to put 'throws' in the method signature. For non-RuntimeException Exceptions, it is required. – Stultuske Mar 16 '23 at 10:18
  • 1
    check [Understanding checked vs unchecked exceptions in Java](https://stackoverflow.com/questions/6115896/understanding-checked-vs-unchecked-exceptions-in-java) – user16320675 Mar 16 '23 at 10:25

1 Answers1

4

I don't know why we need throws keywords

In this case, you don't - because IllegalArgumentException extends RuntimeException. It's therefore not a checked exception, and doesn't need to be declared in a method that throws it.

See the Java tutorial for more details on when you need to use a throws declaration.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you, When a checked exception is thrown, only callers who can handle it properly should catch it with a try/catch. A runtime exception, should not be caught in the program. If you catch it, you run the risk that a bug in the code will be hidden from view at runtime. Is my understanding right? – miao sun Mar 16 '23 at 10:42
  • @miaosun: Not necessarily - you certainly *can* catch RuntimeExceptions, and *sometimes* that's appropriate... but it's less common. – Jon Skeet Mar 16 '23 at 11:02