CS320, Programming Languages - PowerPoint PPT Presentation

1 / 22
About This Presentation
Title:

CS320, Programming Languages

Description:

Exception, in turn has two subclasses RuntimeException and IOException. ... For example, if I define: void buildDist() throws IOException ... – PowerPoint PPT presentation

Number of Views:20
Avg rating:3.0/5.0
Slides: 23
Provided by: cickovt
Category:

less

Transcript and Presenter's Notes

Title: CS320, Programming Languages


1
Exception and Event Handling
  • CS320, Programming Languages

2
Exceptions
  • An exception is an unusual behavior, erroneous or
    not, that
  • Is detectable by hardware or software
  • May require special processing
  • Examples
  • Division by zero (hardware, erroneous)
  • Floating point overflow (hardware, erroneous)
  • Array index out of bounds (software, erroneous)
  • User enters an invalid grade (software,
    user-defined, erroneous)
  • Reading the end of file (hardware, non-erroneous)

3
Exception Handling
  • Involves detecting when a particular exception is
    raised (or thrown)
  • Each exception has a corresponding code segment
    called an exception handler
  • The exception handler can either continue
    execution after handling the unexpected behavior,
    or terminate gracefully
  • Before programming languages provided this
    feature, a program would simply crash upon an
    exception
  • And error messages, if any were produced, would
    often be cryptic

4
Example
  • Suppose either row or col was out of bounds in
    the statement below
  • sum matrowcol
  • The exception that would occur is an array index
    out of bounds
  • The handler for this exception might look like
    this
  • when array_index_out_of_bounds
  • System.out.println(Index range check error on
    mat, row row col col)
  • exit()

5
Continuation
  • Continuation involves a choice between
    termination (ending the program gracefully) or
    resumption (continuing as normal)
  • Resumption requires some modification of values

6
Subprograms and Exceptions
  • If we break a program down into subprograms, each
    subprogram has a certain set of exceptions which
    can occur
  • For example
  • float matrix_avg(float matrowcol, int n)
  • float sum 0.0
  • for (int i 0 i lt row i)
  • for (int j 0 j lt col j)
  • sum matij
  • return sum / n
  • Exceptions that could occur in this function
    include array indexing out of bounds and division
    by zero

7
Why should a language support exception handling?
  • We can do it ourselves. For example, we could
    pass a status parameter by result (or reference,
    or value result)
  • float matrix_avg(float matrowcol, int n, int
    status)
  • // If no exception, set status to 0
  • // If array index out of bounds, set status to
    1 and return
  • // If division by zero (n 0), set status to
    2 and return
  • // etc, etc, etc.
  • Then check status upon return from matrix_avg and
    call the appropriate handler
  • Of course, this is more than a bit ugly
  • We could also pass a label and use gotos, or pass
    actual handlers. Not much cleaner!

8
Exception Handling Features
  • Certainly, its much better to support an
    interface for handling exceptions, such that
  • As a programmer, I can specify the name of an
    exception to be thrown, as opposed to
  • Having to remember which status value
    corresponds to which exception
  • Using gotos
  • Passing a whole bunch of handler routines to
    subprograms
  • Ada, C and Java are known for their exception
    handling facilities
  • Well look at the one people are likely most
    familiar with Java

9
Java
  • Java provides a set of predefined exceptions, and
    the ability to create user-defined exceptions
  • This is done through the Exception class, which
    inherits from Throwable

10
Java
  • Exception, in turn has two subclasses
    RuntimeException and IOException. Both provide
    exceptions which are predefined

11
User-Defined Exceptions
  • I can define my own exception by constructing a
    class which inherits from Exception
  • class MyException extends Exception
  • public MyException()
  • public MyException(String message)
  • super(message)
  • By providing a constructor which accepts an error
    message string, I can control what gets displayed
    when this exception is thrown

12
User-Defined Exceptions
  • I control when it gets thrown by creating a new
    instance of this class and using the Java throw
    statement
  • throw new MyException(Unexpected input value
    input)
  • The superclass constructor immediately displays
    this message when the object is created
  • Any RuntimeException is implicitly thrown a
    user-defined should not inherit from
    RuntimeException
  • I also have to catch any exception by invoking
    the correct handler.

13
Try and Catch
  • I control which subunits of a program can throw
    which exceptions through try and catch blocks
  • try
  • int grade
  • // Get a grade from the user
  • if (grade lt 0 grade gt 100)
  • throw new MyException (Unexpected input
    value input)
  • // Continue
  • catch (MyException e)
  • // If I just want to print the message, this
    can be empty

14
Try and Catch
  • Note I can declare multiple exceptions which all
    inherit from my Exception, and catch each one
  • try
  • catch (MyException e)
  • catch (MyException2 e)
  • catch (Exception e)
  • // Not a typo, this will catch any exception not
    caught by the first two
  • // handlers

15
Associating Exceptions and Subprograms
  • Java allows the throws clause which specifies
    the particular classes of exceptions that can be
    thrown by a subprogram but handled in a caller
    ancestor
  • For example, if I define
  • void buildDist() throws IOException
  • I could have, in some member function
  • try
  • buildDist()
  • catch (IOException e)
  • This way I do not have to catch the exception in
    buildDist() .

16
Predefined Exceptions
  • Java predefined exceptions do not need to be
    explicitly thrown
  • Compiler generates code to throw them if
    necessary
  • They still need to be caught
  • For example
  • try
  • freqindex
  • catch (ArrayIndexOutOfBoundsException)
  • System.out.println(Error Element index
    does not exist)

17
Finally Clause
  • There may be tasks which should be executed
    regardless of whether or not an exception is
    thrown.
  • A common one is closing a file
  • For example, suppose I was repeatedly reading
    integers from a file
  • try
  • // Open a file
  • // Read some integers
  • catch (InvalidInputException e)
  • finally
  • // Close the file

18
Notes on Java Exceptions
  • There are no defaults
  • They cannot be disabled
  • Although Java provides assertions as well, which
    can be disabled
  • Continuation always follows the catch block
  • If no handler is provided for an exception in a
    try block
  • A handler must be provided in a nested try block,
    or
  • The exception must be declared as throwable by
    the encompassing subprogram (remember in Java,
    everything is a subprogram!)
  • And then caught somewhere in the caller ancestry

19
Event Handling
  • In addition to exception handling, we may want
    event handling
  • Similar to exception handling, in that a handler
    is implicitly called upon the occurrence of
    something
  • Unlike exception handling
  • Calls to the handler are not generated by
    exceptions which can occur in hardware or
    software, but by external actions (typically from
    the user). We call these external actions events
    and their handlers event handlers.

20
Java Events
  • Event generators throw events
  • For example, components of a Graphical User
    Interface such as radio buttons or text boxes
  • Event listeners handle events
  • These are registered with event generators
  • When an event is thrown by a generator, each of
    its registered listeners is checked
  • The appropriate listener(s) are invoked

21
Event Generators Examples
  • We can gain access to GUI components by importing
    the Java Swing package, which provides a set of
    graphical objects called widgets
  • import javax.swing
  • The user can interact with a system through the
    widget
  • A text field with 32 characters
  • JTextField name new JTextField(32)
  • A radio button which defaults to on
  • JRadioButton box1 new JRadioButton(Visa,
    true)

22
Creating/Registering Event Listeners
  • class MyApplet extends Applet implements
    ItemListener
  • member variables
  • public void init()
  • define buttons
  • text new JTextField(In what font style
    should I appear, 32)
  • button1.addItemListener(this)
  • button2.addItemListener(this)
  • button3.addItemListener(this)
  • public void itemStateChanged (ItemEvent e)
  • if (button1.isSelected())
    text.setFont(plainFont)
  • else if (button2.isSelected())
    text.setFont(boldFont)
  • else if (button3.isSelected())
    text.setFont(italicFont)
Write a Comment
User Comments (0)
About PowerShow.com