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

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. Commented Mar 16, 2023 at 10:18
  • 1
    check Understanding checked vs unchecked exceptions in Java Commented Mar 16, 2023 at 10:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
@miaosun: Not necessarily - you certainly can catch RuntimeExceptions, and sometimes that's appropriate... but it's less common.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.