Principles of Programming Languages


Exception Handling

  • Topics
    * Introduction to Exception Handling
    * Exception Handling in Ada
    * Exception Handling in C++
    * Exception Handling in Java
    * Functional Programming Language Introduction
    * Mathematical Functions
    * Fundamentals of Functional Programming Languages
    * The First Functional Programming Language: LISP
    * ML
    * Haskell
    * Applications of Functional Languages
    * Comparison of Functional and Imperative Languages
    Introduction to Exception Handling
    * In a language without exception handling
    > When an exception occurs, control goes to the operating system, where a message is displayed and the program is terminated
    * In a language with exception handling
    > Programs are allowed to trap some exceptions, thereby providing the possibility of fixing the problem and continuing
    Basic Concepts
    * Many languages allow programs to trap input/output errors (including EOF)
    * An exception is any unusual event, either erroneous or not, detectable by either hardware or software, that may require special processing
    * The special processing that may be required after detection of an exception is called exception handling
    * The exception handling code unit is called an exception handler
    Exception Handling Alternatives
    * An exception is raised when its associated event occurs
    * A language that does not have exception handling capabilities can still define, detect, raise, and handle exceptions (user defined, software detected)
    * Alternatives:
    > Send an auxiliary parameter or use the return value to indicate the return status of a subprogram
    > Pass an exception handling subprogram to all subprograms
    Advantages of Built-in Exception Handling
    * Error detection code is tedious to write and it clutters the program
    * Exception handling encourages programmers to consider many different possible errors
    * Exception propagation allows a high level of reuse of exception handling code
    Design Issues
    * How are user-defined exceptions specified?
    * Should there be default exception handlers for programs that do not provide their own?
    * Can built-in exceptions be explicitly raised?
    * Are hardware-detectable errors treated as exceptions that can be handled?
    * Are there any built-in exceptions?
    * How can exceptions be disabled, if at all?
    * How and where are exception handlers specified and what is their scope?
    * How is an exception occurrence bound to an exception handler?
    * Can information about the exception be passed to the handler?
    * Where does execution continue, if at all, after an exception handler completes its execution? (continuation vs. resumption)
    * Is some form of finalization provided?
    Exception Handling Control Flow

    Exception Handling in Ada
    * The frame of an exception handler in Ada is either a subprogram body, a package body, a task, or a block
    * Because exception handlers are usually local to the code in which the exception can be raised, they do not have parameters
    Ada Exception Handlers
    * Handler form:
    when exception_choice{|exception_choice} => statement_sequence
    [when others =>
    exception_choice form:
    exception_name | others
    * Handlers are placed at the end of the block or unit in which they occur
    Binding Exceptions to Handlers
    * If the block or unit in which an exception is raised does not have a handler
    for that exception, the exception is propagated elsewhere to be handled
    > Procedures - propagate it to the caller
    > Blocks - propagate it to the scope in which it appears
    > Package body - propagate it to the declaration part of the unit that declared the package (if it is a library unit, the program is terminated)
    > Task - no propagation; if it has a handler, execute it; in either case, mark it "completed"
    * The block or unit that raises an exception but does not handle it is always terminated (also any block or unit to which it is propagated that does not handle it)
    Other Design Choices
    * User-defined Exceptions form:
    exception_name_list : exception;
    * Raising Exceptions form:
    raise [exception_name]
    > (the exception name is not required if it is in a handler--in this case, it propagates the same exception)
    * Exception conditions can be disabled with:
    pragma SUPPRESS(exception_list)
    Predefined Exceptions
    * CONSTRAINT_ERROR - index constraints, range constraints, etc.
    * NUMERIC_ERROR - numeric operation cannot return a correct value (overflow, division by zero, etc.)
    * PROGRAM_ERROR - call to a subprogram whose body has not been elaborated
    * STORAGE_ERROR - system runs out of heap
    * TASKING_ERROR - an error associated with tasks
    * The Ada design for exception handling embodies the state-of-the-art in
    language design in 1980
    * A significant advance over PL/I
    * Ada was the only widely used language with exception handling until it was added to C++
    Exception Handling in C++
    * Added to C++ in 1990
    * Design is based on that of CLU, Ada, and ML
    C++ Exception Handlers
    * Exception Handlers Form:
    try {
    -- code that is expected to raise an exception
    catch (formal parameter) {
    -- handler code
    catch (formal parameter) {
    -- handler code
    The catch Function
    * Catch is the name of all handlers--it is an overloaded name, so the formal parameter of each must be unique
    * The formal parameter need not have a variable
    > It can be simply a type name to distinguish the handler it is in from others
    * The formal parameter can be used to transfer information to the handler
    * The formal parameter can be an ellipsis, in which case it handles all exceptions not yet handled
    Throwing Exceptions
    * Exceptions are all raised explicitly by the statement:
    throw [expression];
    * The brackets are metasymbols
    * A throw without an operand can only appear in a handler; when it appears, it simply re-raises the exception, which is then handled elsewhere
    * The type of the expression disambiguates the intended handler
    Unhandled Exceptions
    * An unhandled exception is propagated to the caller of the function in which it is raised
    * This propagation continues to the main function
    * After a handler completes its execution, control flows to the first statement after the last handler in the sequence of handlers of which it is an element
    * Other design choices
    > All exceptions are user-defined
    > Exceptions are neither specified nor declared
    > Functions can list the exceptions they may raise
    > Without a specification, a function can raise any exception (the throw clause)
    * It is odd that exceptions are not named and that hardware- and system software-detectable exceptions cannot be handled
    * Binding exceptions to handlers through the type of the parameter certainly does not promote readability
    Exception Handling in Java
    * Based on that of C++, but more in line with OOP philosophy
    * All exceptions are objects of classes that are descendants of the Throwable class
    Classes of Exceptions
    * The Java library includes two subclasses of Throwable:
    > Error
    * Thrown by the Java interpreter for events such as heap overflow
    * Never handled by user programs
    > Exception
    * User-defined exceptions are usually subclasses of this
    * Has two predefined subclasses, IOException and RuntimeException (e.g.,
    ArrayIndexOutOfBoundsException and NullPointerException
    Java Exception Handlers
    * Like those of C++, except every catch requires a named parameter and all parameters must be descendants of Throwable
    * Syntax of try clause is exactly that of C++
    * Exceptions are thrown with throw, as in C++, but often the throw includes the new operator to create the object, as in: throw new MyException();
    Binding Exceptions to Handlers
    * Binding an exception to a handler is simpler in Java than it is in C++
    > An exception is bound to the first handler with a parameter is the same class as the thrown object or an ancestor of it
    * An exception can be handled and rethrown by including a throw in the handler (a handler could also throw a different exception)
    * If no handler is found in the method, the exception is propagated to the method‘s caller
    * If no handler is found (all the way to main), the program is terminated
    * To ensure that all exceptions are caught, a handler can be included in any try construct that catches all exceptions
    > Simply use an Exception class parameter
    > Of course, it must be the last in the try construct
    Checked and Unchecked Exceptions
    * The Java throws clause is quite different from the throw clause of C++
    * Exceptions of class Error and RunTimeException and all of their descendants are called unchecked exceptions; all other exceptions are called checked exceptions
    * Checked exceptions that may be thrown by a method must be either:
    > Listed in the throws clause, or
    > Handled in the method
    Other Design Choices
    * A method cannot declare more exceptions in its throws clause than the method it overrides
    * A method that calls a method that lists a particular checked exception in its throws clause has three alternatives for dealing with that exception:
    > Catch and handle the exception
    > Catch the exception and throw an exception that is listed in its own throws clause
    > Declare it in its throws clause and do not handle it
    The finally Clause
    * Can appear at the end of a try construct
    * Form:
    finally {
    * Purpose: To specify code that is to be executed, regardless of what happens in the try construct
    * A try construct with a finally clause can be used outside exception handling
    try {
    for (index = 0; index < 100; index++) {

    if (…) {
    } //** end of if
    } //** end of try clause
    finally {

    } //** end of try construct
    * Statements in the program declaring a boolean expression regarding the current state of the computation
    * When evaluated to true nothing happens
    * When evaluated to false an AssertionError exception is thrown
    * Can be disabled during runtime without program modification or recompilation
    * Two forms
    > assert condition;
    > assert condition: expression;
    * The types of exceptions makes more sense than in the case of C++
    * The throws clause is better than that of C++ (The throw clause in C++ says little to the programmer)
    * The finally clause is often useful
    * The Java interpreter throws a variety of exceptions that can be handled by user programs
    Functional Programming Language Introduction
    * The design of the imperative languages is based directly on the von Neumann architecture
    > Efficiency is the primary concern, rather than the suitability of the language for software development
    * The design of the functional languages is based on mathematical functions
    > A solid theoretical basis that is also closer to the user, but relatively unconcerned with the architecture of the machines on which programs will run
    Mathematical Functions
    * A mathematical function is a mapping of members of one set, called the domain set, to another set, called the range set
    * A lambda expression specifies the parameter(s) and the mapping of a function in the following form
    (x) x * x * x
    for the function cube (x) = x * x * x
    Lambda Expressions
    * Lambda expressions describe nameless functions
    * Lambda expressions are applied to parameter(s) by placing the parameter(s) after the expression
    e.g., ((x) x * x * x)(2)
    which evaluates to 8
    Functional Forms
    * A higher-order function, or functional form, is one that either takes functions as parameters or yields a function as its result, or both
    Function Composition
    * A functional form that takes two functions as parameters and yields a function whose value is the first actual parameter function applied to the application of the second
    Form: h f ° g
    which means h (x) f ( g ( x))
    For f (x) x + 2 and g (x) 3 * x,
    h f ° g yields (3 * x)+ 2
    * A functional form that takes a single function as a parameter and yields a list of values obtained by applying the given function to each element of a list of parameters
    For h (x) x * x
    ( h, (2, 3, 4)) yields (4, 9, 16)
    Fundamentals of Functional Programming Languages
    * The objective of the design of a FPL is to mimic mathematical functions to the greatest extent possible
    * The basic process of computation is fundamentally different in a FPL than in an imperative language
    > In an imperative language, operations are done and the results are stored in variables for later use
    > Management of variables is a constant concern and source of
    complexity for imperative programming
    * In an FPL, variables are not necessary, as is the case in mathematics
    Referential Transparency
    * In an FPL, the evaluation of a function always produces the same result given the same parameters
    LISP Data Types and Structures
    * Data object types: originally only atoms and lists
    * List form: parenthesized collections of sublists and/or atoms
    e.g., (A B (C D) E)
    * Originally, LISP was a typeless language
    * LISP lists are stored internally as single-linked lists
    LISP Interpretation
    * Lambda notation is used to specify functions and function definitions. Function applications and data have the same form.
    e.g., If the list (A B C) is interpreted as data it is
    a simple list of three atoms, A, B, and C
    If it is interpreted as a function application,
    it means that the function named A is
    applied to the two parameters, B and C
    * The first LISP interpreter appeared only as a demonstration of the universality of the computational capabilities of the notation
    * A static-scoped functional language with syntax that is closer to Pascal than to LISP
    * Uses type declarations, but also does type inferencing to determine the types of undeclared variables
    * It is strongly typed (whereas Scheme is essentially typeless) and has no type coercions
    * Includes exception handling and a module facility for implementing abstract data types
    * Includes lists and list operations
    ML Specifics
    * Function declaration form:
    fun name (parameters) = body;
    e.g., fun cube (x : int) = x * x * x; - The type could be attached to return value, as in fun cube (x) : int = x * x * x; - With no type specified, it would default to
    int (the default for numeric values) - User-defined overloaded functions are not allowed, so if we wanted a cube function for real parameters, it would need to have a different name
    - There are no type coercions in ML
    * ML selection if expression then then_expression else else_expression
    where the first expression must evaluate to a Boolean value
    * Pattern matching is used to allow a function to operate on different parameter forms fun fact(0) = 1 | fact(n : int) : int = n * fact(n – 1)
    * Lists Literal lists are specified in brackets [3, 5, 7] [] is the empty list CONS is the binary infix operator, :: 4 :: [3, 5, 7], which evaluates to [4, 3, 5, 7] CAR is the unary operator hd CDR is the unary operator tl fun length([]) = 0 | length(h :: t) = 1 + length(t); fun append([], lis2) = lis2 | append(h :: t, lis2) = h :: append(t, lis2);
    * The val statement binds a name to a value (similar to DEFINE in Scheme) val distance = time * speed; - As is the case with DEFINE, val is nothing like an assignment statement in an imperative language
    * Similar to ML (syntax, static scoped, strongly typed, type inferencing, pattern matching)
    * Different from ML (and most other functional languages) in that it is purely functional (e.g., no variables, no assignment statements, and no side effects of any kind)
    Syntax differences from ML fact 0 = 1 fact n = n * fact (n – 1) fib 0 = 1
    fib 1 = 1
    fib (n + 2) = fib (n + 1) + fib n
    Function Definitions with Different Parameter Ranges
    fact n | n == 0 = 1 | n > 0 = n * fact(n – 1) sub n | n < 10 = 0 | n > 100 = 2 | otherwise = 1 square x = x * x - Works for any numeric type of x
    * List notation: Put elements in brackets
    e.g., directions = ["north", "south", "east", "west"]
    * Length: #
    e.g., #directions is 4
    * Arithmetic series with the .. operator
    e.g., [2, 4..10] is [2, 4, 6, 8, 10]
    * Catenation is with ++
    e.g., [1, 3] ++ [5, 7] results in [1, 3, 5, 7]
    * CONS, CAR, CDR via the colon operator (as in Prolog)
    e.g., 1:[3, 5, 7] results in [1, 3, 5, 7]
    Factorial Revisited
    product [] = 1
    product (a:x) = a * product x
    fact n = product [1..n]
    List Comprehension
    * Set notation
    * List of the squares of the first 20 positive integers: [n * n | n [1..20]]
    * All of the factors of its given parameter:
    factors n = [i | i [1..n div 2],
    n mod i == 0]
    sort [] = []
    sort (a:x) =
    sort [b | b x; b <= a] ++
    [a] ++
    sort [b | b x; b > a]
    Lazy Evaluation
    * A language is strict if it requires all actual parameters to be fully evaluated
    * A language is nonstrict if it does not have the strict requirement
    * Nonstrict languages are more efficient and allow some interesting capabilities – infinite lists
    * Lazy evaluation - Only compute those values that are necessary
    * Positive numbers
    positives = [0..]
    * Determining if 16 is a square number
    member [] b = False
    member(a:x) b=(a == b)||member x b
    squares = [n * n | n ← [0..]]
    member squares 16
    Member Revisited
    *The member function could be written as:
    member [] b = False
    member(a:x) b=(a == b)||member x b
    * However, this would only work if the parameter to squares was a perfect square; if not, it will keep generating them forever. The following version will always work:
    member2 (m:x) n
    | m < n = member2 x n
    | m == n = True
    | otherwise = False
    Applications of Functional Languages
    * APL is used for throw-away programs
    * LISP is used for artificial intelligence
    > Knowledge representation
    > Machine learning
    > Natural language processing
    > Modeling of speech and vision
    * Scheme is used to teach introductory programming at some universities
    Comparing Functional and Imperative Languages
    * Imperative Languages:
    > Efficient execution
    > Complex semantics
    > Complex syntax
    > Concurrency is programmer designed
    * Functional Languages:
    > Simple semantics
    > Simple syntax
    > Inefficient execution
    –Programs can automatically be made concurrent
    * Ada provides extensive exception-handling facilities with a comprehensive set of built-in exceptions.
    * C++ includes no predefined exceptions Exceptions are bound to handlers by connecting the type of expression in the throw statement to that of the formal parameter of the catch function
    * Java exceptions are similar to C++ exceptions except that a Java exception must be a descendant of the Throwable class. Additionally Java includes a finally clause
    * Functional programming languages use function application, conditional expressions, recursion, and functional forms to control program execution instead of imperative features such as variables and assignments
    * LISP began as a purely functional language and later included imperative features
    * Scheme is a relatively simple dialect of LISP that uses static scoping exclusively
    * COMMON LISP is a large LISP-based language
    * ML is a static-scoped and strongly typed functional language which includes type inference, exception handling, and a variety of data structures and abstract data types
    * Haskell is a lazy functional language supporting infinite lists and set comprehension.
    * Purely functional languages have advantages over imperative alternatives, but their lower efficiency on existing machine architectures has prevented them from enjoying widespread use
    1) What are the design issues that are involved in exception handling?
    2) Explain the basic concepts of exception handling.
    3) Explain the uses of exception handling in programming languages.
    4) What is exception handling? How it can be implemented in Ada? Explain with examples.
    5) Explain exception handling in C++ with example.
    6) How can exceptions be explicitly raised in C++? Explain
    7) Explain exception handling in Java.
    8) Explain how exception bind to handlers in java.
    9) In what way C++ ‘throw’ specification differs from clause in java?
    10) Explain fact statements and rule statements in prolog.
    11) Explain prolog inferencing process.
    12) All prolog statements are constructed from terms. Justify your answer.
    13) Discuss terms and goal statements in prolog?
    14) Discuss about basic elements of prolog. Give examples.

Industry      Interaction

Higher Education

Job Skills

Soft Skills

Comm. English

Mock Test