Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling, part 2 Reference: R.Sebesta, Chapter 14

Similar presentations


Presentation on theme: "Exception Handling, part 2 Reference: R.Sebesta, Chapter 14"— Presentation transcript:

1 Exception Handling, part 2 Reference: R.Sebesta, Chapter 14
COS220 Concepts of PLs AUBG, COS dept Lecture 15 Exception Handling, part 2 Reference: R.Sebesta, Chapter 14 7/23/2018 Assoc. Prof. Stoyan Bonev

2 Assoc. Prof. Stoyan Bonev
Lecture Contents: Reminder: Intro to Exception Handling Reminder: Basic Concepts and Definitions Advantages of having Exception Handling Structured EH in VBasic Exceptions and errors generated by C++ classes Quiz 4 on EH 7/23/2018 Assoc. Prof. Stoyan Bonev

3 Exception Handling-Introduction
Most computer HW systems are capable of detecting certain run-time error conditions as: zero division FP overflow I/O (Read/Write) disk errors Or specific situations as END-OF-DATA END-OF-FILE 7/23/2018 Assoc. Prof. Stoyan Bonev

4 Exception Handling-Introduction
Many PL are designed and implemented in a way that user programs can neither detect nor deal with errors and specific cases. In those PL, occurrence of an error simply causes the program to terminate and control to transfer back to OS. The typical OS reaction to a run-time error is to display diagnostic message (meaningful or highly cryptic) and to terminate the program. 7/23/2018 Assoc. Prof. Stoyan Bonev

5 Exception Handling-Introduction
There is a category of serious errors that are not detectable by HW, but should be SW detectable, e.g. by code generated by the compiler. For example, array subscript range errors are almost never detected by HW, but they do lead to fatal addressing errors, that are registered later during program run. Detection of subscript range errors is sometimes required by the language design (Java). Subscript ranges are not checked in C, C++. Subscript range checking may be selectively switched on/off using a compiler option. 7/23/2018 Assoc. Prof. Stoyan Bonev

6 Assoc. Prof. Stoyan Bonev
EH – Basic Concepts Both the errors detected by hardware (as disk read errors) and unusual conditions such as end-of-file (also detected by hardware) are being termed as exceptions. The concept of exceptions is further extended to include errors or unusual conditions that are software detectable. 7/23/2018 Assoc. Prof. Stoyan Bonev

7 Assoc. Prof. Stoyan Bonev
EH – Definitions Exception – any unusual event (erroneous or not) that is detectable either by hardware or by software and that may require special processing. Exception Handling – a special processing that may be required by the detection of an exception. Exception Handler – a program code that is used to do the special processing, i.e. exception handling Exception is raised when the associated event occurs. 7/23/2018 Assoc. Prof. Stoyan Bonev

8 Part 2a Structured EH in VBasic

9 Assoc. Prof. Stoyan Bonev
Modern EH in VBasic As opposed to the traditional techniques used to deal with errors, Visual Basic now supports a technique referred to as exception handling. This technique was mostly used by other languages such as C++, Object Pascal, Java, C#, etc. This technique is also referred to as structured exception handling (SEH). The On Error GoTo system of dealing with errors is referred to as unstructured exception handling (we will abbreviate is unSEH). There were many concerns with unSEH used in previous versions of Visual Basic 7/23/2018 Assoc. Prof. Stoyan Bonev

10 Problems(1) with unSEH in VB
In previous versions, you had to remember to include On Error GoTo sometimes in a random area inside the procedure. Besides On Error GoTo, you had to remember to create a label section. The name of the label had to be faithfully included in the On Error GoTo line. This technique was not really the most precise system. 7/23/2018 Assoc. Prof. Stoyan Bonev

11 Problems(2) with unSEH in VB
When using the On Error GoTo technique, you had to make sure you get out of the procedure at the right time, which was done using an Exit Sub line. If you created this Exit Sub line in the wrong area in your procedure, either the whole code would not be considered or undesired section of the procedure would still execute, possibly producing an unpredictable result. In the same way, a bizarre way of creating a Resume or a Resume Next line would prevent the compiler from reaching or considering some sections of a procedure 7/23/2018 Assoc. Prof. Stoyan Bonev

12 Assoc. Prof. Stoyan Bonev
Because of these uncertainties, you should abandon the On Error GoTo traditional error handling and use SEH in all of your new code. Because SEH and unSEH techniques are inherently different, you cannot use both in the same procedure. 7/23/2018 Assoc. Prof. Stoyan Bonev

13 Assoc. Prof. Stoyan Bonev
Try to Catch the Error As mentioned already, errors are likely going to occur in your program. The more you anticipate them and take action, the better your application can be. We have already seen that syntax errors are usually human mistakes such as misspelling, bad formulation of expressions, etc. The compiler will usually help you fix the problem by pointing it out. SEH is based on two main keywords: Try and Catch. An exception handling section starts with the Try keyword and stops with the End Try statement. Between Try and End Try, there must by at least one Catch section. Therefore, exception handling uses the following formula: 7/23/2018 Assoc. Prof. Stoyan Bonev

14 Assoc. Prof. Stoyan Bonev
Try ' Code to Execute In Case ' Everything is alright Catch ' If Something Bad happened, ' deal with it here End Try 7/23/2018 Assoc. Prof. Stoyan Bonev

15 Assoc. Prof. Stoyan Bonev
Exception handling always starts with the Try keyword. Under the Try line, Write the normal code that the compiler must execute. Here is an example: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim Number As Double Dim Twice As Double Try Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice End Try End Sub 7/23/2018 Assoc. Prof. Stoyan Bonev

16 Assoc. Prof. Stoyan Bonev
As the compiler is treating code in the Try section, if it encounters a problem, it "gets out" of the Try section and starts looking for a Catch section. Therefore, you MUST always have a Catch section. If you don't, as seen on the above code, the program will not compile. A Catch section must be written before the End Try line: 7/23/2018 Assoc. Prof. Stoyan Bonev

17 Assoc. Prof. Stoyan Bonev
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim Number As Double Dim Twice As Double Try Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice Catch End Try End Sub 7/23/2018 Assoc. Prof. Stoyan Bonev

18 Assoc. Prof. Stoyan Bonev
When the Catch keyword is simply written as above, it would be asked to treat any error that occurs. For example, if you execute the above code with a number such as 24$.58 instead of , nothing would appear to happen. This would indicate that the error was found and vaguely dealt with. One problem in this case is that the compiler would not bother to let the user know why there is no result displayed. Because there can be various types of errors in a program, you also should make your program more intuitive and friendlier so that, when an error occurs, the user would know the type of problem. This is also useful if somebody calls you and says that your program is not functioning right. If there is a way the user can tell you what exact type of error is displaying, may be you would find the solution faster. 7/23/2018 Assoc. Prof. Stoyan Bonev

19 Visual Basic and Exception Handling
The Exception Class

20 Assoc. Prof. Stoyan Bonev
In traditionally-oriented error dealing languages such as C/C++ or Object Pascal, you could create any exception of your choice, including numeric or strings. To customize exception handling, you could also create your own class. Most libraries such as Borland's VCL and Microsoft's MFC also shipped with their own classes to handle exceptions. Even the Win32 library provides its type of mechanism to face errors. To support exception handling, the .NET Framework provides the Exception class. Once the compiler encounters an error, the Exception class allows you to identify the type of error and take appropriate action. Normally, Exception mostly serves as the general class of exceptions. Anticipating various types of problems that can occur in a program, Microsoft derived various classes from Exception to make this issue friendlier. As a result, almost any type of exception you may encounter already has a class created to deal with it. Therefore, when your program faces an exception, you can easily identify the type of error. There are so many exception classes that we cannot study or review them all. The solution we will use is to introduce or review a class when we meet its type of error. 7/23/2018 Assoc. Prof. Stoyan Bonev

21 The Exception's Message
In exception handling, errors are dealt with in the Catch section. To do this, on the right side of Catch, declare a variable of the type of exception you want to deal with. By default, an exception is first of type Exception. Based on this, a typical formula to implement exception handling is: Try Catch ex As Exception End Try 7/23/2018 Assoc. Prof. Stoyan Bonev

22 Assoc. Prof. Stoyan Bonev
When an exception occurs in the Try section, code compilation is transferred to the Catch section. If you declare the exception as an Exception type, this class will identify the error. One of the properties of the Exception class is called Message. This property contains a string that describes the type of error that occurred. You can then use this message to display an error message if you want. Here is an example: 7/23/2018 Assoc. Prof. Stoyan Bonev

23 Assoc. Prof. Stoyan Bonev
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim Number As Double Dim Twice As Double Try Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice Catch ex As Exception MsgBox(ex.Message) End Try End Sub 7/23/2018 Assoc. Prof. Stoyan Bonev

24 Here is an example of running the program:
7/23/2018 Assoc. Prof. Stoyan Bonev

25 Assoc. Prof. Stoyan Bonev
Custom Error Messages The above test shows us that the Exception class knows with certainty what problem occurred and why the operation could not be carried. Sometimes, the message provided by the Exception class may not appear explicit enough. In fact, you may not want to show it to the user since, as in this case, the user may not understand what the word "cast" in this context means and why it is being used. As an alternative, you can create your own message and display it to the user. Here is an example: 7/23/2018 Assoc. Prof. Stoyan Bonev

26 Assoc. Prof. Stoyan Bonev
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim Number As Double Dim Twice As Double Try Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice Catch ex As Exception MsgBox("The operation could not be carried because " & vbCrLf & "the number you typed is invalid", _ MsgBoxStyle.OKOnly, "Invalid Operation") End Try End Sub 7/23/2018 Assoc. Prof. Stoyan Bonev

27 Here is an example of running the program:
7/23/2018 Assoc. Prof. Stoyan Bonev

28 Assoc. Prof. Stoyan Bonev
You can also combine the Exception.Message message and your own message: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim Number As Double Dim Twice As Double Try Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice Catch ex As Exception MsgBox(ex.Message & vbCrLf & "The operation could not be performed since " & vbCrLf & "the number you provided is not valid", MsgBoxStyle.OKOnly, "Invalid Operation") End Try End Sub 7/23/2018 Assoc. Prof. Stoyan Bonev

29 Here is an example of running the program:
7/23/2018 Assoc. Prof. Stoyan Bonev

30 Exception Derived Classes
To deal with the various types of errors that can occur in a large procedure, the .NET Framework provides various classes derived from Exception. Each of these classes tend to deal with a particular error that could occur when using a certain control. Because there are so many of them, we will mention some of them. 7/23/2018 Assoc. Prof. Stoyan Bonev

31 Classes derived from Exception
ArgumentOutOfRangeException IndexOutOfRangeException InvalidCastException NullReferenceException OverflowException IO.DirectoryNotFoundException IO.FileNotFoundException IO.EndOfStreamException IO.IOException Source: Schneider, pp 420 7/23/2018 Assoc. Prof. Stoyan Bonev

32 In Case of Error, Throw This
When a problem in a particular section of a procedure, you can indicate this to the compiler and "throw" an error. This is done with the Throw keyword, which is usually included in the Try section. The formula used is: Try ' Code to Execute In Case ' Everything is alright Throw Catch ' If Something Bad happened, ' deal with it here End Try 7/23/2018 Assoc. Prof. Stoyan Bonev

33 Part 2b Exceptions and errors generated by user defined C++ classes

34 Assoc. Prof. Stoyan Bonev
Exceptions and OOP Exceptions provide systematic, OO approach to handling errors generated by C++ classes. Exceptions are errors that occur at runtime. Typical exceptional circumstances: Running out of memory; Not being able to open a file; Trying to initialize an object to an impossible value; Using out-of-bounds index of a vector. 7/23/2018 Assoc. Prof. Stoyan Bonev

35 Assoc. Prof. Stoyan Bonev
EH before OOP C-language programs signal an error by returning a particular value from the function in which the exception occurred. Each time you call one of these functions, you check the return value. 7/23/2018 Assoc. Prof. Stoyan Bonev

36 Assoc. Prof. Stoyan Bonev
The fragment of source text func1(); // proceed normally func2(); func3(); func4(): Should be replaced with (see next slide) 7/23/2018 Assoc. Prof. Stoyan Bonev

37 Assoc. Prof. Stoyan Bonev
if ( func1() == ErrRetVal ) // handle the error else // proceed normally if ( func2() == ErrRetVal ) if ( func3() == ErrRetVal ) if ( func4() == ErrRetVal ) 7/23/2018 Assoc. Prof. Stoyan Bonev

38 Problems with EH old style
Problem 1: Each single call to a function must be examined. Surrounding each function call with an if … else statement and error handling statements adds a lot of code and makes listing hard to read. 7/23/2018 Assoc. Prof. Stoyan Bonev

39 Problems with EH old style
Problem 2: In OOP constructors are implicitly called functions and they have no return values. How will the program find out if error occurred in class constructor? No way to insert if statements to check the value returned by the constructor 7/23/2018 Assoc. Prof. Stoyan Bonev

40 Problems with EH old style
Problem 3: Class libraries and program implementation. It is very hard to arrange for error values to be communicated from a class member function to the program that’s calling that function. The problem of communicating errors from deep within class libraries is the most important problem solved by exceptions. 7/23/2018 Assoc. Prof. Stoyan Bonev

41 Problems with EH old style
Problems 1, 2, 3 come to show that a new error handling mechanism is must.. 7/23/2018 Assoc. Prof. Stoyan Bonev

42 Assoc. Prof. Stoyan Bonev
Exception Syntax Given an application that creates and interacts with object of a certain class. Usually application calls to class methods cause no problems. Sometimes, application makes a mistake, causing an error to be detected in a method. This method then informs the application that error has occurred. This is called throwing an exception. In the application we install a separate section of code to handle the error. This code is called exception handler or catch block. It catches the exception thrown by the class method. Any code in the application that uses objects of the class is enclosed in a try block. 7/23/2018 Assoc. Prof. Stoyan Bonev

43 Assoc. Prof. Stoyan Bonev
Exception Syntax Illustration 7/23/2018 Assoc. Prof. Stoyan Bonev

44 Exception – ideology example
class AClass { public: class AnError // exception class }; void Func() // member f unction if (error cond) throw AnError(); } // void main() // application try AClass obj1; // interact with AClass objects obj1.Func(); // may cause error catch (AClass::AnError) // exception handler with naked (type only) formal parameter // tell user about error 7/23/2018 Assoc. Prof. Stoyan Bonev

45 Simple Working Example
.

46 Assoc. Prof. Stoyan Bonev
EH with classes in C++ Demo program: Source text: SBExcept5.cpp Executable code: SBExcept5.exe 7/23/2018 Assoc. Prof. Stoyan Bonev

47 Simple Working Example 1/2
const int MAX = 3; class Stack { private: int st[MAX]; int top; public: class Range // exception class for Stack { // note: empty class body }; Stack() { top = -1; } void push(int var) if (top >= MAX-1) throw Range(); st[++top] = var; } int pop() { if (top < 0) throw Range(); return st[top--]; 7/23/2018 Assoc. Prof. Stoyan Bonev

48 Simple Working Example 2/2
void main() { Stack c; try c.push(11); c.push(22); c.push(33); c.push(44); cout << endl << "1: " << c.pop(); cout << endl << “2: " << c.pop(); cout << endl << “3: " << c.pop(); cout << endl << “4: " << c.pop(); } catch(Stack::Range) cout << endl << "Exception: Stack full or empty"; cout << endl << "Arrive here after catch or normal exit "; 7/23/2018 Assoc. Prof. Stoyan Bonev

49 Specifying the Exception Class
// exception class for Stack class Range { // note: empty class body }; 7/23/2018 Assoc. Prof. Stoyan Bonev

50 Throwing the Exception
if (top >= MAX-1) throw Range(); if (top < 0) throw Range(); 7/23/2018 Assoc. Prof. Stoyan Bonev

51 Assoc. Prof. Stoyan Bonev
The try Block try { // code that operates on objects that // might cause an exception } c.push(11); c.push(22); c.push(33); c.push(44); cout << endl << "1: " << c.pop(); cout << endl << “2: " << c.pop(); cout << endl << “3: " << c.pop(); cout << endl << “4: " << c.pop(); cout << endl << “5: " << c.pop(); 7/23/2018 Assoc. Prof. Stoyan Bonev

52 The EHandler (catch Block)
catch(Stack::Range) { // code that handles the exception } cout << “\nException: Stack full or empty"; 7/23/2018 Assoc. Prof. Stoyan Bonev

53 Assoc. Prof. Stoyan Bonev
Sequence of Events Code is executing normally outside a try block. Control enters the try block. A statement in the try block causes an error in a member function. The member function throws an exception. Control transfers to the exception handler. 7/23/2018 Assoc. Prof. Stoyan Bonev

54 You can design a class to throw as many exceptions as you want.
Multiple Exceptions You can design a class to throw as many exceptions as you want.

55 Assoc. Prof. Stoyan Bonev
EH with classes in C++ Demo program: Source text: SBExcept6.cpp Executable code: SBExcept6.exe 7/23/2018 Assoc. Prof. Stoyan Bonev

56 Multiple Exceptions (1/2)
#include <iostream> using namespace std; const int MAX = 3; class Stack { private: int st[MAX]; int top; public: class Full {}; // exception class for Stack class Empty{}; // note: empty class body Stack() { top = -1; } void push(int var) if (top >= MAX-1) throw Full(); st[++top] = var; } int pop() if (top < 0) throw Empty(); return st[top--]; }; 7/23/2018 Assoc. Prof. Stoyan Bonev

57 Multiple Exceptions (2/2)
void main() { Stack c; try c.push(11); c.push(22); c.push(33); //c.push(44); cout << endl << "1: " << c.pop(); cout << endl << "2: " << c.pop(); cout << endl << "3: " << c.pop(); cout << endl << "4: " << c.pop(); } catch(Stack::Full) cout << endl << "Exception: Stack full"; catch(Stack::Empty) cout << endl << "Exception: Stack empty"; cout << endl << "Arrive here after catch or normal exit "; 7/23/2018 Assoc. Prof. Stoyan Bonev

58 Exceptions with the Distance class

59 Assoc. Prof. Stoyan Bonev
Distance class Problem: inches should always be <12.0 Class cannot protect itself in case the user initializes instance of the Distance class like Distance d1(10, 14.5); Distance d2; d2.GetDist(); 7/23/2018 Assoc. Prof. Stoyan Bonev

60 Assoc. Prof. Stoyan Bonev
EH with classes in C++ Demo program: Source text: SBExcept7.cpp Executable code: SBExcept7.exe 7/23/2018 Assoc. Prof. Stoyan Bonev

61 Exception with Distance class 1/2
class Distance { private: int feet; float inches; public: class InchesEx {}; // exception class for Distance Distance() { feet=0; inches = 0.0; } Distance(int ft, float in) { if (in >= 12.0) throw InchesEx(); feet = ft; inches = in; } void GetDist() { cout <<"\nEnter feet:"; cin >> feet; cout <<"\nEnter inches:"; cin >> inches; if (inches >= 12.0) throw InchesEx(); void ShowDist() { cout << feet << "\'-" << inches << '\"'; }; 7/23/2018 Assoc. Prof. Stoyan Bonev

62 Exception with Distance class 2/2
void main() { try Distance d1(17, 4.5); Distance d2; d2.GetDist(); cout << "\n d1 = "; d1.ShowDist(); cout << "\n d2 = "; d2.ShowDist(); cout << endl; } catch(Distance::InchesEx) cout << endl << "Initialization error: inches value >= 12.0"; 7/23/2018 Assoc. Prof. Stoyan Bonev

63 Exceptions with Arguments

64 Exceptions with Arguments
How to proceed if the application needs more info about what caused an exception For previous Distance example: What the bad value for inches exactly was By which member function was the exception thrown: the 2-arg Constructor or the GetDist() method? How to pass such an info from the member function where the exception was thrown to the application that catches it Throwing an exception involves not only control transfer to the EHandler but also creating an object of the exception class by calling its constructor 7/23/2018 Assoc. Prof. Stoyan Bonev

65 Exceptions with Arguments
Solution is to define exception class that: Is not empty Is regular class with data components and at least constructor 7/23/2018 Assoc. Prof. Stoyan Bonev

66 Assoc. Prof. Stoyan Bonev
EH with classes in C++ Demo program: Source text: SBExcept8.cpp Executable code: SBExcept8.exe 7/23/2018 Assoc. Prof. Stoyan Bonev

67 Exceptions with Arguments 1/2
class Distance { private: int feet; float inches; public: class InchesEx // exception class for Distance public: string origin; // for name of routine float ivalue; // for faulty inches value InchesEx(string or, float in) { origin = or; ivalue = in; } }; Distance() { feet=0; inches = 0.0; } Distance(int ft, float in) { if (in >= 12.0) throw InchesEx("2-arg constructor", in); feet = ft; inches = in; } void GetDist() { cout <<"\nEnter feet:"; cin >> feet; cout <<"\nEnter inches:"; cin >> inches; if (inches >= 12.0) throw InchesEx("GetDist() method", inches); void ShowDist() { out << feet << "\'-" << inches << '\"'; 7/23/2018 Assoc. Prof. Stoyan Bonev

68 Exceptions with Arguments 2/2
void main() { try Distance d1(17,44.5); Distance d2; d2.GetDist(); cout << "\n d1 = "; d1.ShowDist(); cout << "\n d2 = "; d2.ShowDist(); cout << endl; } catch(Distance::InchesEx ix) cout << endl << "Initialization error in: "<< ix.origin; cout << endl << ix.ivalue << " inches value >= 12.0"; 7/23/2018 Assoc. Prof. Stoyan Bonev

69 Specifying data in an Exception class
class InchesEx // exception class for Distance { public: string origin; // for name of routine float ivalue; // for faulty inches value InchesEx(string or, float in) origin = or; ivalue = in; } }; 7/23/2018 Assoc. Prof. Stoyan Bonev

70 Initializing an Exception object
In the 2-arg constructor if (in >= 12.0) throw InchesEx("2-arg constructor", in); In GetDist() member function if (inches >= 12.0) throw InchesEx("GetDist() method", inches); 7/23/2018 Assoc. Prof. Stoyan Bonev

71 Extracting Data from the Exception Object
catch(Distance::InchesEx ix) { // access ix.origin and ix.ivalue directly cout << endl << "Initialization error in: "<< ix.origin; cout << endl << ix.ivalue << " inches value >= 12.0"; } 7/23/2018 Assoc. Prof. Stoyan Bonev

72 Standard C++ contains several built-in classes
The bad_alloc class

73 C++ built-in exception classes
The most commonly used is the bad_alloc class which is thrown if an error occurs when attempting to allocate heap memory with the new operator. 7/23/2018 Assoc. Prof. Stoyan Bonev

74 bad_alloc Exception class
#include <iostream> using namespace std; int main() { const unsigned long SIZE = 10000; char* ptr; try ptr = new char[SIZE]; } catch(bad_alloc) cout << "\nBad_alloc exception. Can't allocate memory."; return 1; delete[] ptr; cout << "\n memory use is successful"; return 0; 7/23/2018 Assoc. Prof. Stoyan Bonev

75 Quiz 4 on EH

76 Exception Handling and Event Handling
Chapter 14 Exception Handling and Event Handling Source: Longman dictionary 1987 76

77 Chapter 14 Topics Introduction to Exception Handling
Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Introduction to Event Handling Event Handling with Java Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-77 Source: Longman dictionary 1987 77

78 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-78 Source: Longman dictionary 1987 78

79 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-79 Source: Longman dictionary 1987 79

80 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 a label parameter to all subprograms (error return is to the passed label) Pass an exception handling subprogram to all subprograms Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-80 Source: Longman dictionary 1987 80

81 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-81 Source: Longman dictionary 1987 81

82 Design Issues (continued)
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? Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-82 Source: Longman dictionary 1987 82

83 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? Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-83 Source: Longman dictionary 1987 83

84 Exception Handling Control Flow
Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-84 Source: Longman dictionary 1987 84

85 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-85 Source: Longman dictionary 1987 85

86 Ada Exception Handlers
Handler form: when exception_choice{|exception_choice} => statement_sequence ... [when others => statement_sequence] exception_choice form: exception_name | others Handlers are placed at the end of the block or unit in which they occur Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-86 Source: Longman dictionary 1987 86

87 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" Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-87 Source: Longman dictionary 1987 87

88 Continuation 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) Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-88 Source: Longman dictionary 1987 88

89 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) Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-89 Source: Longman dictionary 1987 89

90 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-90 Source: Longman dictionary 1987 90

91 Evaluation The Ada design for exception handling embodies the state-of-the-art in language design in 1980 Ada was the only widely used language with exception handling until it was added to C++ Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-91 Source: Longman dictionary 1987 91

92 Exception Handling in C++
Added to C++ in 1990 Design is based on that of CLU, Ada, and ML Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-92 Source: Longman dictionary 1987 92

93 C++ Exception Handlers
Exception Handlers Form: try { -- code that is expected to raise an exception } catch (formal parameter) { -- handler code ... Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-93 Source: Longman dictionary 1987 93

94 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-94 Source: Longman dictionary 1987 94

95 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-95 Source: Longman dictionary 1987 95

96 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 If no handler is found, the default handler is called Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-96 Source: Longman dictionary 1987 96

97 Continuation 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 The default handler, unexpected, simply terminates the program; unexpected can be redefined by the user Functions can list the exceptions they may raise Without a specification, a function can raise any exception (the throw clause) Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-97 Source: Longman dictionary 1987 97

98 Evaluation 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-98 Source: Longman dictionary 1987 98

99 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-99 Source: Longman dictionary 1987 99

100 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-100 Source: Longman dictionary 1987 100

101 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(); Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-101 Source: Longman dictionary 1987 101

102 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) Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-102 Source: Longman dictionary 1987 102

103 Continuation If no handler is found in the try construct, the search is continued in the nearest enclosing try construct, etc. 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 insure 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-103 Source: Longman dictionary 1987 103

104 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-104 Source: Longman dictionary 1987 104

105 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-105 Source: Longman dictionary 1987 105

106 The finally Clause Can appear at the end of a try construct Form:
... } Purpose: To specify code that is to be executed, regardless of what happens in the try construct Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-106 Source: Longman dictionary 1987 106

107 Example A try construct with a finally clause can be used outside exception handling try { for (index = 0; index < 100; index++) { if (…) { return; } //** end of if } //** end of try clause finally { } //** end of try construct Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-107 Source: Longman dictionary 1987 107

108 Assertions 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; Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-108 Source: Longman dictionary 1987 108

109 Evaluation 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-109 Source: Longman dictionary 1987 109

110 Introduction to Event Handling
An event is created by an external action such as a user interaction through a GUI The event handler is a segment of code that is called in response to an event Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-110 Source: Longman dictionary 1987 110

111 Java Swing GUI Components
Text box is an object of class JTextField Radio button is an object of class JRadioButton Applet’s display is a frame, a multilayered structure Content pane is one layer, where applets put output GUI components can be placed in a frame Layout manager objects are used to control the placement of components Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-111 Source: Longman dictionary 1987 111

112 The Java Event Model User interactions with GUI components create events that can be caught by event handlers, called event listeners An event generator tells a listener of an event by sending a message An interface is used to make event-handling methods conform to a standard protocol A class that implements a listener must implement an interface for the listener Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-112 Source: Longman dictionary 1987 112

113 The Java Event Model (continued)
One class of events is ItemEvent, which is associated with the event of clicking a checkbox, a radio button, or a list item The ItemListener interface prescribes a method, itemStateChanged, which is a handler for ItemEvent events The listener is created with addItemListener Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-113 Source: Longman dictionary 1987 113

114 Summary 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 An event is a notification that something has occurred that requires handling by an event handler Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-114 Source: Longman dictionary 1987 114

115 Thank You For Your Attention


Download ppt "Exception Handling, part 2 Reference: R.Sebesta, Chapter 14"

Similar presentations


Ads by Google