- So once an error object is thrown, there
must be some object out there ready to catch it and process it.
Unlike throwing errors, however, catching errors takes a bit more
consideration.
- Specifically, you must use "try-catch" blocks
to insulate the greater program from errors in methods. Try-catch blocks
work like this. Your program tries to perform some method that has
the potential to cause an error. If it succeedes, great. If not, it
uses a catch statement block to perform error handling. Generically, it
looks something like the following:
try
{
some code that may throw an
error object;
}
catch (ExceptionType e)
{
Deal with the exception object
that we have named "e";
}
- Thus, if an error object is thrown from the
try block, it will be handled in the catch block. Thus, any method
that might throw an error must be contained within a try-catch block
and the catch block must be prepared to handle the error objects that
might be thrown.
- If multiple error objects are thrown, the catch
block must deal with each individually such as in the case below:
try
{
some code that may throw an
error object;
}
catch (MalformedURLException e)
{
Deal with the problematic URL;
}
catch (IOException e)
{
Deal with the IO exception;
}
- Typically, your catch block will contain code
to warn the user that they need to enter their data in some other
format or that the request they have is unacceptable. However, it
can also be used to gracefully exit the program and print an error log
for you to use later.
- Finally, Java provides the "finally" clause that
executes whether or not an exception is caught. This is particularly
useful for cleanup operations in case of serious errors.
try
{
some code that may throw an
error object;
}
catch (MalformedURLException e)
{
Deal with the problematic URL;
}
finally
{
always executed;
}
Previous Page |
Next Page
|