Transcript catch

Java Programming
Exceptions
Exceptions
• Java has a built in mechanism for error handling and
trapping errors
• Usually this means dealing with abnormal events or code
execution that prevents the program from continuing
–
–
–
–
Array out of bounds accesses
Divide by zero
Null pointers
To name a few…
• Exceptions allow us to handle these events automatically
when they happen
What are Exceptions?
• An Exception is a Java class
• There are many subclasses of the Exception class, each
corresponding to a different type of error or abnormal
event that we wish to handle
• Basic concept:
– When one of these abnormal events occurs, Java will throw an
Exception
– This means that it will instantiate a subclass of the Exception
class
– Whenever an Exception could possibly be thrown, you must
provide a mechanism for catching it in your code
Throwing Exceptions
• Essentially, throwing exceptions in Java is a way of
terminating method execution early:
public class String
{
public char charAt(int index)
throws IndexOutOfBoundsException
{
. . .
throw new IndexOutOfBoundsException();
. . .
return c;
}
}
Catching Exceptions
• Anytime that you call a method that has been declared
as being able to throw an Exception, you can catch the
Exception using a try/catch block:
try {
String text = “text”;
System.out.println(text.charAt(10));
} catch(IndexOutOfBoundsException e) {
System.err.println(“Index out of bounds”);
e.printStackTrace();
}
• If an Exception is thrown inside of a try block, the
exception that is returned is forwarded as an argument
to the catch block where the Exception can be handled
Catching Exceptions
• In most cases, if a method can throw an Exception and
you want to call it, you must deal with it
• However, if the Exception that the method throws is a
subclass of the RunTimeException class, then you do
not need to explicitly catch the Exception (this includes
IndexOutOfBoundsException from the previous
example)
• If a RunTimeException is thrown and not caught, Java
will automatically abort the program and print the stack
trace of the exception
RunTimeException
• These are the subclasses of the RunTimeException
class
–
–
–
–
–
–
–
–
–
–
–
ArithmeticException
IndexOutOfBoundsException
NegativeArraySizeException
NullPointerException
ArrayStoreException
ClassCastException
IllegalArgumentException
SecurityException
IllegalMonitorStateException
IllegalStateException
UnsupportedOperationException
Dealing with Exceptions
• As we have seen, if a method throws an Exception that
is not a subclass of RunTimeException, we are required
to deal with it if using this method
• One way is by using a try/catch block as we have seen
• You can also indicate that the calling method throws the
same Exception, essentially forwarding the responsibility
of catching the exception to the code that calls your
method
public void myMethod()
throws IOException
{
//calls a method that throws an IOException
}
Multiple catch blocks
• Sometimes, a method can throw more than one possible
Exception, or the try block could call two different
methods that throw two different Exceptions
try {
String text = “text”;
System.out.println(text.charAt(10));
int n = Integer.parseInt(“abc”);
} catch(IndexOutOfBoundsException e) {
System.err.println(“Index out of bounds”);
e.printStackTrace();
} catch(NumberFormatException e) {
System.err.println(“bad number”);
e.printStackTrace();
}
Multiple catch blocks
• Since all Exceptions are subclasses of the Exception
class, you can generalize catch blocks to accept multiple
different types of Exceptions by using a super class
try {
String text = “text”;
System.out.println(text.charAt(10));
int n = Integer.parseInt(“abc”);
} catch(Exception e) {
System.err.println(“Something bad happened”);
e.printStackTrace();
}
The finally block
• Sometimes when you call a try/catch block, an Exception
could be thrown before some important code that needs
to be run at the end of the try block
• The finally block can be used to run this code
• Even if an exception is thrown, the finally block will
always execute
try {
String text = “text”;
System.out.println(text.charAt(10));
} catch(IndexOutOfBoundsException e) {
System.err.println(“Index out of bounds”);
e.printStackTrace();
} finally {
//important code
}
Rethrowing Exceptions
• You can “rethrow” an exception after catching it and
processing it
try {
String text = “text”;
System.out.println(text.charAt(10));
} catch(IndexOutOfBoundsException e) {
System.err.println(“Index out of bounds”);
e.printStackTrace();
throw e;
}
• If you rethrow an Exception, you must specify that the
calling method throws the Exception
Exceptions
• What type of information can you get from Exception
objects?
– getCause()
– getMessage()
– printStackTrace()
• Sub classes of Exception can be much more elaborate
and contain more information if desired
• You can also define your own Exception class which
must be a subclass of Exception or one of its subclasses
ที่มา
• Rensselaer Polytechnic Institute: Owen Kellett