Throwing Exceptions

You can also throw your own exceptions if something unexpected happens in your code. To do that, write:

throw new Exception("description of problem");

when the unexpected state occurs. If the error occurs in a method, you can throw an exception instead of returning a value. Here’s an example:

public void divide(int a, int b) 
{
    if (b == 0) 
    {
        throw new Exception("Division by zero");
    }
    else return a/b;
}

When I call divide, it will either return a value or it will throw an exception. I could try/catch my call to divide as follows:

int a, b;
//get user input for a and b

try 
{
    int result = divide(a, b);
    System.out.println(result);
}
catch(Exception e) 
{
    //will print "Division by zero"
    System.out.println(e.getMessage());
}

If I use the try/catch block, the program will not crash if I try to divide by zero. Alternatively, if I call divide without using a try/catch, the program will crash and the exception message (“Division by zero”) will get printed.