Exceptions offer the possibility to avoid cluttering program code with exception handling. An exception can be thrown when something unexpected happens. The exception is then caught, either by an invoking method, or by the default exception handler which prints a call stack.
public class MyException extends Exception { public String reason; /* constructor */ MyException(String s) { super("MyException with reason: " + s + "."); reason = s; } }
public void doit(int i) throws MyException { if (i == 0) throw MyException("argument was 0"); }
try { int i = 0; doit(i); System.out.println("There was no exception"); } catch (MyException e) { // handle the exception System.out.println("An exception was generated"); }When a method contains method calls that may generate exceptions it must either catch the exceptions or declare that it throws these exceptions itself (or both if it catches the exceptions in some places and not in other places).
try { int i = 1; doit(i); return 1; // try to return 1, but won't work } catch (MyException e) { // do nothing for now } finally { return 2; // this will be returned in any case }