O'Reilly logo

Java Garage by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required