DOC PREVIEW
UT CS 345 - Exception specifications and class derivation

This preview shows page 1 out of 2 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 2 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 2 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

CS 345 slide 353 Spring 200526 April 2005Exception specifications and class derivationVirtual overrides’ exception specifications must be atleast as restrictive as their bases’.class Base {public: virtual void f(); // can throw anything virtual void g() throw( X, Y ); virtual void h() throw( X );};class Derived : public Base { void f() throw( X ); // OK void g() throw( X ); // OK void h() throw( X, Y );// error};Otherwise, a caller of Base::h() would be unpreparedto handle a Y thrown by Derived::h().For the same reason,void f() throw( X );void (*pf1)() throw( X, Y ) = &f; // OKvoid (*pf2)() throw( ) = &f; // errorCS 345 slide 354 Spring 200526 April 2005Error Handling in JavaGarbage collector  no destructorsMemory resources are released automatically; otherresources can be released in a finally clause.If C++ had finally blocks:void useFile( const char* fn ) { FILE* f = fopen( fn, “w” ); try { // use f } finally { fclose( f ); }}A finally block is always executed, regardless ofwhether an exception is thrown.It is executed after any of its try block’s exceptionhandlers:class Switch { boolean state = false; boolean read() { return state; } void on() { state = true; } void off() { state = false; }}// ...static Switch sw = new Switch();CS 345 slide 355 Spring 200526 April 2005public static void main( ... ) { try { sw.on(); // Code that can throw exceptions... } catch( NullPointerException e ) { // ...handle it ... } catch( IllegalArgumentException e ) { // ...handle it ... } finally { sw.off(); }}In Java, all classes are derived from Object; allexception classes are derived from Throwable.The Java counterpart of C++’scatch ( ... ) { /* ... /* }iscatch ( Throwable ) { /* ... /* }with the advantage that Throwable has a few methodscatch ( Throwable e ) { ... e.getMessage() ... e.toString() ...}CS 345 slide 356 Spring 200526 April 2005Classes derived from Throwable include• Exception• RunTimeException• ErrorIn Java, functions’ exception specificationsvoid f() throws tooBig, tooSmall { // ...are checked by the compiler (in C++ they are checkedonly at run time).If f —or any function called by f— throws anyexception (other than tooBig and tooSmall) whose typeis Exception or any of its subtypes, this causes acompilation error.Exception and its subtypes —which include the vastmajority of exception types— are known as checkedexception types.Hence a function that lacks an exception specificationis guaranteed to throw no checked exceptions:void g() { // ...indicates that g• throws no checked exceptions itself• handles every checked exception thrown by thefunctions it callsThe unchecked exception types —RunTimeException,Error, and their derivatives— are not checked by thecompiler:• RunTimeException —includes NullPointerException,ArrayIndexOutOfBoundsException, and others resultingfrom programming errors• Error — indicates a system errorCS 345 slide 357 Spring 200526 April 2005Error Handling in HaskellIn programming languages that lack the notion of“flow of control”, the try-throw-catch method ofexception handling is not a good fit.In Haskell, errors occur when a partial function —i.e.,a function which is undefined for certain arguments—causes a computation to halt with an error.Example: Applying the function> tail :: [a] -> [a]> tail (_:xs) = xsto an empty list [] halts the entire program:Main> tail (tail [2])Program error: {tail []}What’s needed is a functional counterpart ofexception handling— i.e., a way to enablecomputations to handle errors and continue.This means transforming partial functions like tailinto total functions.One technique: Replace each partial function with onethat returns a list.> tail' :: [a] -> [a]> tail' (_:xs) = xs> tail' [] = []Problem: The “error” case is indistinguishable fromcertain non-error cases:> tail' [3] H S []> tail' [] H S []CS 345 slide 358 Spring 200526 April 2005Another problem: For functions that don’t returnlists, this technique doesn’t work at all:> head' :: [a] -> a> head' (x:_) = x> head' [] = ???We could change the functions’ types:> tail'' :: [a] -> [[a]]> tail'' (_:xs) = [xs]> tail'' [] = []> head'' :: [a] -> [a]> head'' (x:_) = [x]> head'' [] = []This works, but —unlike exceptions in C++/Java— itdoesn’t clearly distinguish the normal-case code fromthe error-handling code.Error “results” can be distinguished from valid resultsby defining a polymorphic algebraic type:> data Maybe a = Nothing | Just a> deriving (Eq, Ord, Read, Show)Maybe a is like a type of “boxes” for values of type a,with a label on the outside of each box indicatingwhether it contains a good value.Functions that are not total —i.e., functions which,applied to certain arguments, halt the computation—can be redefined to return boxed values.Instead of a partial function whose type isa -> bwe define a total function of typea -> Maybe bCS 345 slide 359 Spring 200526 April 2005Following this approach with head and tail, we write> mTail :: [a] -> Maybe [a]> mTail (x:xs) = Just xs> mTail [] = Nothing -- exception value> mHead :: [a] -> Maybe a> mHead (x:_) = Just x> mHead [] = NothingThis technique works for division by 0:Instead of> div :: Int -> Int -> Intwhich does not survive 0 divisors:Prelude> 3 `div` 0Program error: {primQrmInteger 3 0}or> div' :: Int -> Int -> Int> div' a b> | b /= 0 = a `div` b> | otherwise = 0which conceals 0 divisors, we write> mDiv :: Int -> Int -> Maybe Int> mDiv a b> | b /= 0 = Just (a `div` b)> | otherwise = NothingThese functions —mTail, mHead, and mDiv — are said toraise exceptions when they can’t produce a normalresult.CS 345 slide 360 Spring 200526 April 2005Using MaybeA function that raises exceptions:try p s applies parser p to string s.If p succeeds, delivering an item r and consuming allof s, then try p s returns Just r ; otherwise, try p sreturns Nothing.> try :: Parser a -> String -> Maybe a> try p s> = case [ r | (r,"") <- papply p s ] of> (r:_) -> Just r> [] -> NothingA function that tests for exceptions:get prompt p outputs prompt, then inputs a line andapplies parser p to it.If the parser recognizes the line, get returns therecognized item; otherwise, it repeats.> get :: String -> Parser a -> IO a> get prompt p> = do putStr prompt> line


View Full Document

UT CS 345 - Exception specifications and class derivation

Download Exception specifications and class derivation
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Exception specifications and class derivation and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Exception specifications and class derivation 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?