Java Reference
In-Depth Information
// women >= 0 && men >= 0
if (women >= men)
System.out.println("Each man must dance with " +
women/( double )men + " women.");
else
System.out.println("Each woman must dance with " +
men/( double )women + " men.");
}
This try block contains the following three throw statements:
throw
statement
throw new Exception("Lesson is canceled. No students.");
throw new Exception("Lesson is canceled. No men.");
throw new Exception("Lesson is canceled. No women.");
The value thrown is an argument to the throw operator and is always an object of some
exception class. The execution of a throw statement is called throwing an exception .
throwing an
exception
throw Statement
SYNTAX
throw new Exception_Class_Name ( Possibly_Some_Arguments );
When the throw statement is executed, the execution of the surrounding try block is stopped
and (normally) control is transferred to a catch block. The code in the catch block is executed
next. See the box entitled “ try-throw-catch ” later in this chapter for more details.
EXAMPLE
throw new Exception("Division by zero.");
As the name suggests, when something is “thrown,” something goes from one place
to another place. In Java, what goes from one place to another is the flow of control as
well as the exception object that is thrown. When an exception is thrown, the code in
the surrounding try block stops executing and (normally) another portion of code,
known as a catch block , begins execution. The catch block has a parameter, and the
exception object thrown is plugged in for this catch block parameter. This executing
of the catch block is called catching the exception or handling the exception . When
an exception is thrown, it should ultimately be handled by (caught by) some catch
block. In Display 9.2, the appropriate catch block immediately follows the try block.
We repeat the catch block in what follows:
catch block
handling an
exception
catch (Exception e)
{
String message = e.getMessage();
System.out.println(message);
System.exit(0);
}
Search WWH ::




Custom Search