Exception Handling
Exception Handling
Oriented
Programming
Exception Handling
What is an exception?
class MyClass {
void oops()
{ if (/* no error occurred */)
{ /* normal processing */ }
else { /* error occurred */
throw new MyException();
}
} //oops
}//class MyClass
Exceptional flow of control
Error
“unchecked”, thus need not be in ‘throws’ clause
Serious system problems (e.g. ThreadDeath,
OutOfMemoryError)
It’s very unlikely that the program will be able to recover, so
generally you should NOT catch these.
RuntimeException
“unchecked”, thus need not be in ‘throws’ clause
Also can occur almost anywhere, e.g. ArithmeticException,
NullPointerException, IndexOutOfBoundsException
Try to prevent them from happening in the first place!
System will print stop program and print a trace
Catching an exception
print("now");
try
{ print("is ");
throw new MyException();
print("a ");
}
catch(MyException e) { print("the "); }
print("time\n");
Prints "now is the time".
Note that exceptions don't have to be used only for error handling
Would it be a good idea to exceptions for non-error processing?
But any other use is likely to result in code that's hard to
understand.
Declaring an exception type