Throwing exception in main method
exception, java
Solution
You only throw an exception if you want it to be handled by a "higher" function.
(Note: The exception doesn't just disappear when it is thrown. It still has to be handled.)
public void functionA() throws Exception{
throw new Exception("This exception is going to be handled elsewhere");
}
You use a `try/catch` block when you want to handle the exception immediately.
public void functionB(){
try{
throw new Exception("This exception is handled here.");
}catch(Exception e){
System.err.println("Exception caught: "+e);
}
}
If you are already using a `try/catch` block to catch an exception, then you have no need to throw that exception any higher.
public void functionC() throws Exception{
try{
throw new Exception("This exception doesn't know where to go.");
}catch(Exception e){
System.err.println("Exception caught: "+e);
}
}
Problem
I am trying to figure out why I have to `throw` exception in the main method while I have `try`/`catch` blocks that can handle those exceptions anyway? Even if I delete `throws IllegalArgumentException,InputMismatchException` part, the program will still compile and work perfectly. ``` public static void main(String[] args) throws IllegalArgumentException,InputMismatchException{ boolean flag = true; Scanner in = new Scanner(System.in); do{ try{ System.out.println("Please enter the number:"); int n = in.nextInt(); int sum = range(n); System.out.println("sum = " + sum); flag = false; } catch(IllegalArgumentException e){ System.out.println(e.getMessage()); } catch(InputMismatchException e){ System.out.println("The number has to be as integer..."); in.nextLine(); } ```