Exception Handling Exceptions and language features to handle them.
-
Upload
katherine-miller -
Category
Documents
-
view
224 -
download
0
Transcript of Exception Handling Exceptions and language features to handle them.
Exception unusual condition that occurs during
execution of a program may be error or not may be hardware or software based detected by
hardware (end-of-file) OS (file-not-found) PL (division-by-zero) program (test for zero denominator)
Exception handling
response to exception being detected terminate program ignore exception (temporarily) ‘handle’ exception within program –
special code to execute
Programmed exception handling
who handles the exception? procedure executing when exception is
raised calling procedure
provides instructions to called procedure by passing procedure parameter or reference
receives notification by return value from called procedure
special exception communication features in the language
design of exception handling
possible functions defining exceptions detecting and identifying exceptions propagating exceptions intercepting exceptions binding exceptions to handlers resolving exceptions
design of exception handling
features complete structure (eg Pascal procedure,
java class) or code segment? one general handler or many specific
handlers? program continuation options programmer control – defining &
detecting exceptions, defining handlers?
use of exception handling features
simplify code – remove error handling ‘clutter’
focus programmer attention on program correctness
give more program control in response to errors
use exceptions as legitimate design tool – not just for errors
open questions
should hardware errors be part of exception handling process?
should there be a default exception handling system?
should programmers have power to disable exceptions?
PL/I system pre-defined exceptions
e.g. ZERODIVIDE, ENDFILE(source) system default handlers – SYSTEM to use defaults:
ON SUBSCRIPTRANGE SYSTEM; /* redundant */...
(SUBSCRIPTRANGE): X(I) = Y(I+1) * 2; some exceptions always on, some
default on, some default off
PL/Iprogrammer can: create new exceptions
CONDITION BADINPUT; /* declaration */ raise (throw) the exception:
SIGNAL (X > 100) BADINPUT; trap and handle the exception like a
system exception
PL/I
to handle programmer exceptions ORto override SYSTEM handlers exception handlers are code segments
execute in environment where codedON <EXCEPTION_NAME>BEGIN; <statememts> END;
scope of control to end of block to next handler with same exception
PL/I
e.g. user defined exception declare, handle and throw
CONDITION BADINPUT
ON BADINPUT
BEGIN;
< code to handle exception>
END;
...
SIGNAL (X>100) BADINPUT;
PL/I exception handling problems
dynamic binding of handlers to exceptions is flexible but can be misleading: wrong handler can respond to raised exceptione.g. – several handlers for SUBSCRIPTRANGE associated with different arrays
complex continuation rules (what to do after handler executes)
Ada handlers are code segments in procedure
or block scope, at the end of the block static binding of exception to handler
after handler executes, procedure or block terminates, returns control to caller
unhandled exceptions propegated through dynamic links until handler found
if no handler found, task or program terminates
C++ try – throw – catch structure like java system exceptions and programmer
exceptions are distinct – programmer can’t handle system exceptions
anything can be thrown as exception (primitive or object) – no predefined exception classes
caught exceptions can be rethrown to caller
Java try – throw – catch structure with a
finally block option exceptions are legitimate objects in the
Throwable hierarchy some ‘handling’ can occur in the exception
object constructor as well as the catch continuation:
catch handlers can rethrow exceptions or throw different ones
hander can use return to terminate method otherwise execution continues after try/catch
block
class Throwable only objects that can be thrown by
jvm or by program contains
snapshot of execution stack for this thread
string message (maybe) cause (chain)- reference to another
throwable (trace history when one exception is caught and another is thrown) - recursive
class Error extends Throwable constructors
with / without message with / without cause
methods all inherited from Throwable
Errors should not be caught - serious abnormal conditions that should cause termination (“unchecked”)
class Exception extends Throwable
constructors with / without message with / without cause
methods all inherited from Throwable
Exceptions must be caught* - abnormal but manageable conditions that should be handled by program (“checked”)
* except RuntimeExceptions, next slide
class RuntimeException extends Exception
constructors with / without message with / without cause
methods all inherited from Throwable
RuntimeExceptions do not have to be caught - errors that should not occur (“unchecked”)
Java – exception classes unchecked exceptions (Error,
RuntimeException and subclasses) assumed throwable and propagatable from any class
checked exceptions (Exception) complier verifies that any exceptions a method throws are either caught or declared in header
which and why?? the official word
extending Error
AnnotationFormatError, AssertionError, AWTError, CoderMalfunctionError, FactoryConfigurationError, FactoryConfigurationError, IOError, LinkageError, ServiceConfigurationError, ThreadDeath, TransformerFactoryConfigurationError, VirtualMachineError
extending Exception - catch these AclNotFoundException, ActivationException, AlreadyBoundException, ApplicationException,
AWTException, BackingStoreException, BadAttributeValueExpException, BadBinaryOpValueExpException, BadLocationException, BadStringOperationException, BrokenBarrierException, CertificateException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, DatatypeConfigurationException, DestroyFailedException, ExecutionException, ExpandVetoException, FontFormatException, GeneralSecurityException, GSSException, IllegalAccessException, IllegalClassFormatException, InstantiationException, InterruptedException, IntrospectionException, InvalidApplicationException, InvalidMidiDataException, InvalidPreferencesFormatException, InvalidTargetObjectTypeException, InvocationTargetException, IOException, JAXBException, JMException, KeySelectorException, LastOwnerException, LineUnavailableException, MarshalException, MidiUnavailableException, MimeTypeParseException, MimeTypeParseException, NamingException, NoninvertibleTransformException, NoSuchFieldException, NoSuchMethodException, NotBoundException, NotOwnerException, ParseException, ParserConfigurationException, PrinterException, PrintException, PrivilegedActionException, PropertyVetoException, RefreshFailedException, RemarshalException, RuntimeException, SAXException, ScriptException, ServerNotActiveException, SOAPException, SQLException, TimeoutException, TooManyListenersException, TransformerException, TransformException, UnmodifiableClassException, UnsupportedAudioFileException, UnsupportedCallbackException, UnsupportedFlavorException, UnsupportedLookAndFeelException, URIReferenceException, URISyntaxException, UserException, XAException, XMLParseException, XMLSignatureException, XMLStreamException, XPathException
extending RuntimeException AnnotationTypeMismatchException, ArithmeticException, ArrayStoreException,
BufferOverflowException, BufferUnderflowException, CannotRedoException, CannotUndoException, ClassCastException, CMMException, ConcurrentModificationException, DOMException, EmptyStackException, EnumConstantNotPresentException, EventException, IllegalArgumentException, IllegalMonitorStateException, IllegalPathStateException, IllegalStateException, ImagingOpException, IncompleteAnnotationException, IndexOutOfBoundsException, JMRuntimeException, LSException, MalformedParameterizedTypeException, MirroredTypeException, MirroredTypesException, MissingResourceException, NegativeArraySizeException, NoSuchElementException, NoSuchMechanismException, NullPointerException, ProfileDataException, ProviderException, RasterFormatException, RejectedExecutionException, SecurityException, SystemException, TypeConstraintException, TypeNotPresentException, UndeclaredThrowableException, UnknownAnnotationValueException, UnknownElementException, UnknownTypeException, UnmodifiableSetException, UnsupportedOperationException, WebServiceException
syntax of exceptions - Java… preceding codetry{
…code may throw Exceptions}catch (MyException mE){ \\ exception handler … exception handling code
}catch (MyNextException nE){
… handling by throwing new Exception}
… more exception handlersfinally{
… must be executed}
… following code
syntax of exceptions - Java… preceding codetry{
…code may throw Exceptions}catch (MyException mE){
… exception handling code}
catch (MyNextException nE){… handling by throwing new Exception}
… more exception handlersfinally{
… must be executed}
… following code
control flow with
1. no exception in try
2. exception caught by MyException
3. exception caught by MyNextException
4. exception not caught
control flow with
1. no exception in try
2. exception caught by MyException
3. exception caught by MyNextException
4. exception not caught