Exceptions: When Things Go Wrong

Download Report

Transcript Exceptions: When Things Go Wrong

Exceptions: When things go
wrong
• Topics to be covered:
– What is an exception
– Throwing an exception
– Catching an exception
Expecting the unexpected
• When you design a program, you develop
an algorithm for what’s supposed to happen;
but, as we all know, life doesn’t always
work that way. Example:
– The user enters a floating point number instead
of a integer
– You try to evaluate X / Y, when Y has the value
0
– You try to access position 10 in an array with
10 elements
Example
public class Exception1
{ public static void main(String [] args)
{
int x = 1, y = 0;
int z = x/y;
System.out.println("Finished!");
}
}
Screen Output:
Exception in thread “main” java.lang.ArithmeticException: / by zero
at Exception1.main(Exception1.java:7)
Exceptions are objects
• When something goes wrong we need to do
something about it
• Exceptions are objects that contain
information about what went wrong and
where it happened
– The getMessage() method returns a string
explaining the exception
Exception in thread “main” java.lang.ArithmeticException: / by zero
– The printStackTrace() method prints the call
stack trace
at Exception1.main(Exception1.java:7)
Exception class hierarchy
Object
Throwable
Error
Exception
RunTimeException
ArithmeticException
IndexOutOfBoundsException
You can define your own
exceptions
Creating your own exception
public class MyException extends Exception
{
public MyException(String message)
{
super(message);
}
}
Another (silly) example
public class Exception2
{ public static void main(String [] args)
{
int x = 1, y = 0;
System.out.println("Starting the calculations");
int ans = calculations(x,y);
System.out.println("The answer is: " + ans);
}
public static int calculations(int x, int y)
{
int ans = division(x,y);
return ans;
}
public static int division(int x, int y)
{
int z = x/y;
return z;
}
}
Normal control flow
main()
calculations()
division()
Execution begins in main()
which invokes calculations()
which then invokes division().
When division() finishes
control returns to calculations()
and then from there to main().
When an exception is generated
main()
calculations()
division()
OH NO!
When a method has a problem, it generates an exception
object.
It then throws the exception back along the call path.
The exception travels along the call path until it is caught
by a compatible catch statement.
The catch statement may exist in the method where the
exception was first generated or in any other method
on the call path.
The throw clause
• A method must declare that it may throw an exception
• This information is as much a part of its normal
header as its return type or its parameters
public static int division(int x, int y) throws MyException
• The information lets anyone calling the method know
that they must be prepared for it to throw this
exception
• A throw statement is a little like a return statement
except that a method may throw more than one
exception and each exception may be of a different
type
Throwing an exception
public class Exception2
{ public static void main(String [] args) throws MyException
{
int x = 1, y = 0;
System.out.println("Starting the calculations");
int ans = calculations(x,y);
System.out.println("The answer is: " + ans);
}
public static int calculations(int x, int y) throws MyException
{
int ans = division(x,y);
return ans;
}
public static int division(int x, int y) throws MyException
{
int z = 0;
if(y==0) { MyException exceptionObj =
new MyException("Division would be undefined");
throw exceptionObj;
} else
z = x/y;
return z;
}
}
The screen output
Starting the calculations
Exception in thread "main" MyException: Division
would be undefined
at Exception2.division(Exception2.java:19)
at Exception2.calculations(Exception2.java:12)
at Exception2.main(Exception2.java:7)
Press any key to continue...
Catching an exception
• If a throw statement is like return statement, then a
try/catch statement is a little like an if/else
statement.
• Statements that may throw an exception must be
enclosed in a try block---this is just a regular block
of code preceded by the key word try
• The try block is followed by a catch block, which
gives the instructions to execute if an exception of
the specified type is caught
– The catch clause always has a single parameter
specifying the exception to be caught
– The catch body is executed only if an exception
of the appropriate type is thrown
A try/catch example
public class Exception2
{ …
public static int calculations(int x, int y)
{
…
}
public static int division(int x, int y)
{
int z = 0;
try {
if(y==0) { MyException eObj = new
MyException("Division would be undefined");
throw eObj;
} else
z = x/y;
}
catch(MyException e)
{
System.out.println("The exception message is: " + e.getMessage());
}
return z;
}
}
The screen output
Starting the calculations
The exception message is: Division would be
undefined
The answer is: 0
Press any key to continue...
Points to remember
• The try body contains statements that may throw
an exception; at least one statement in the block
must potentially throw an exception
• Each catch block has a parameter that defines the
type of exception it can catch
• If a method catches an exception, it stops the
propagation of that exception up the call path.
Methods with appropriate try/catch blocks do not
have throw declarations in their headers.
public static int division(int x, int y) throws MyException
NO