Tradional way
to
handle runtime error
- When a method execution
encounters an
error, the
method would
return an
error code
- Example:
public static void main(String[] args)
{
double area = areaOfCircle( -4 );
if ( area == -1 ) // Check error code
{
System.out.println("Error");
}
}
public static double areaOfCircle( double radius )
{
if ( radius < 0 )
return -1; // Error code
else
return 3.1415 * radius * radius;
}
|
|
DEMO:
demo/02-review/ErrorCode.java
Modern way
to
handle runtime error
DEMO:
demo/02-review/ThrowException.java
Modern way
to
handle runtime error
- You can
test (= catch) for the
"error code" (exception type)
and execute a block when the
"error code" is
detected:
- Example:
public static void main(String[] args)
{
try // Indicates that statements may return an "error code"
{
double area = areaOfCircle( -4 );
}
catch (RuntimeException e) // Test if "error code" = RunTime..
{
System.out.println("Error: " + e);
System.out.println("... continue...");
}
System.out.println("DONE");
}
public static double areaOfCircle( double radius )
{
if ( radius < 0 )
throw new RuntimeException("***neg radius***");
else
return 3.1415 * radius * radius;
}
|
|
DEMO:
demo/02-review/CatchException.java
❮
❯