Exceptions

Throwing an exception means that you don't want to deal with it: You will let the caller handle it (or pass the buck too). Declare that your method throws an exception using the throws keyword, like this:

public void someMethod() throws Exception {
    if(somethingBad) {
    throw new Exception("Something bad happened: ");
    }
}

If you are using library code that throws an exception and you don't want to deal with it in a try/catch block, you can just say that your method throws this exception, and not think about it.

Alternatively, you can catch an exception to handle the problem inside the method, as shown here:

 public void someMethod() { // code for an operation that could cause an // exception... try { // ...some code } catch(Exception ...

Get Java Garage now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.