Download presentation
Presentation is loading. Please wait.
Published byToby Allen Modified over 6 years ago
1
Exception Handling, part 1 Reference: R.Sebesta, Chapter 14
COS220 Concepts of PLs AUBG, COS dept Lecture 14 Exception Handling, part 1 Reference: R.Sebesta, Chapter 14 4/23/2018 Assoc. Prof. Stoyan Bonev
2
Assoc. Prof. Stoyan Bonev
Lecture Contents: Introduction to Exception Handling Basic Concepts and Definitions Advantages of exploring EH Design Issues Exception Handling Techniques in: Fortran, PL/1, Basic, Pascal, C, Ada, C++, Java, C#, VBasic 4/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 4/23/2018 Assoc. Prof. Stoyan Bonev
4
Exception Handling-Introduction
Many old 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. 4/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. A/ Detection of subscript range errors is sometimes required by the language design (Java). B/ Subscript ranges are not checked in C, C++. C/ Subscript range checking may be selectively switched on/off using a compiler option. 4/23/2018 Assoc. Prof. Stoyan Bonev
6
Exception Handling-Introduction
Many modern PL provide mechanisms that take action when some hardware-detectable and/or software-detectable conditions occur. These conditions allow the programmer to define other unusual events and deal with them when they arise. These mechanisms are collectively called EXCEPTION HANDLING. 4/23/2018 Assoc. Prof. Stoyan Bonev
7
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. 4/23/2018 Assoc. Prof. Stoyan Bonev
8
Exceptions and Interrupts
Control is the most challenging aspect of processor design. One of the hardest parts of control is implementing exceptions and interrupts. Exception is an unexpected event from within the processor: arithmetic overflow is an example of an exception. Interrupt is an event that also causes an unexpected change in control flow but comes from outside of the processor. Interrupts are used by I/O devices to communicate with processor. 4/23/2018 Assoc. Prof. Stoyan Bonev
9
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. 4/23/2018 Assoc. Prof. Stoyan Bonev
10
Assoc. Prof. Stoyan Bonev
Exception Handlers EHandlers are different for specific exception types. Detection of end-of-file always requires some specific program action. Detection of FP overflow requires other specific program action. Some other cases require generation of error message and termination of a program. It may be desirable to ignore certain exceptions for a time. Such an exception is disabled. A disabled exception can later be enabled. 4/23/2018 Assoc. Prof. Stoyan Bonev
11
Advantages of exploring EH
1. Without EH the code required to detect errors can considerably clutter the program. 2. Exception propagation. It allows an exception raised in one program unit to be handled in some other unit, i.e. a single EHandler to be reused for a large number of different program units. 3. A PL that supports EH encourages its users to consider all the events that could occur during program execution and how they can be handled on. This results to solid and reliable code. 4/23/2018 Assoc. Prof. Stoyan Bonev
12
Assoc. Prof. Stoyan Bonev
Design Issues EH system is considered as a part of PL. Such a system might allow both: Built-in exceptions and EHandlers User-defined exceptions and EHandlers The basic concept of EH is introduced on the skeletal program unit that appears on next slide. 4/23/2018 Assoc. Prof. Stoyan Bonev
13
Assoc. Prof. Stoyan Bonev
// typical C-like program unit without // Exception Handling support // there is a dangerous division operator specified void example() { . . . average = sum / total; return; } // end of program unit example 4/23/2018 Assoc. Prof. Stoyan Bonev
14
Assoc. Prof. Stoyan Bonev
// typical C-like program unit with Exception Handling support void example() { . . . average = sum / total; return; // exception handlers when zero_divide average=0; cout<<”\nErr:divisor(total) is zero”; } // other exception handlers } // end of program unit example 4/23/2018 Assoc. Prof. Stoyan Bonev
15
Assoc. Prof. Stoyan Bonev
Design Issues Form of user-defined EHandler How is an exception occurence bound to an EHandler Control continuation after EHandler execution 4/23/2018 Assoc. Prof. Stoyan Bonev
16
Assoc. Prof. Stoyan Bonev
Design Issue 1: Form of user-defined EHandler is a choice between: A/ Having EHandlers that are complete program units. B/ Having EHandlers that are code segments. In case of B/ EHandlers may be: Embedded in the unit that raise the exception as in the example above Embedded in a different unit, such as the unit that called the unit that raised the exception 4/23/2018 Assoc. Prof. Stoyan Bonev
17
Assoc. Prof. Stoyan Bonev
Design Issue 2: How is an exception occurence bound to an EHandler This issue appears on two different levels: On the unit level; At a higher level. 4/23/2018 Assoc. Prof. Stoyan Bonev
18
Exception bound on unit level
The question is how the same exception (division by zero, for example) being raised in different points in a unit can be bound to different handlers within the same unit. 4/23/2018 Assoc. Prof. Stoyan Bonev
19
Exception bound at higher level
The binding question arises when there is no EHandler local to the unit in which the exception is raised. So, the designer must decide whether to propagate the exception to some other unit and if so, where (usually, the caller unit) or to ignore it. It’s a compromise between: 4/23/2018 Assoc. Prof. Stoyan Bonev
20
Exception bound at higher level
Local handlers. If EHandlers must be local, then many handlers must be written, which complicates writing and reading programs. Global handlers. If exceptions are propagated, a single EHandler might handle the same exception raised in several different units, which may require the handler to be more general than one would prefer. 4/23/2018 Assoc. Prof. Stoyan Bonev
21
Assoc. Prof. Stoyan Bonev
Design Issue 3: Control continuation after EHandler execution. Here is a list of possible solutions: Program termination: obviously the simplest choice but not the best in case of non fatal errors or non erroneous situations. The choice to continue is better. Where? Return to statement that raised the exception. Return to statement that follows the statement that raised the exception. Return to the end of the unit that raised the exception. Return to an explicitly declared statement within or outside the unit that raised the exception. 4/23/2018 Assoc. Prof. Stoyan Bonev
22
Assoc. Prof. Stoyan Bonev
EH control flow 4/23/2018 Assoc. Prof. Stoyan Bonev
23
Assoc. Prof. Stoyan Bonev
4/23/2018 Assoc. Prof. Stoyan Bonev
24
Assoc. Prof. Stoyan Bonev
EH in Fortran INTEGER A, B READ(5,10) A,B 10 FORMAT(2I6) Fortran provides primitive branches for input errors and end-of-file conditions. 4/23/2018 Assoc. Prof. Stoyan Bonev
25
Assoc. Prof. Stoyan Bonev
EH in Fortran READ(5,10) A,B READ(5,10,END=100,ERR=20) A,B FORMAT(2I6) . . . CONTINUE I/O ERROR CONTINUE END OF DATA Fortran provides primitive branches for input errors and end-of-file conditions. 4/23/2018 Assoc. Prof. Stoyan Bonev
26
Assoc. Prof. Stoyan Bonev
EH in PL/1 PL/1 provides built-in and user-defined exceptions ON <condition> <stmt/compound stmt>; CONDITION <exception name>; SIGNAL(<exception name>); Any condition can be explicitly raised with SIGNAL stmt, although the built-in exceptions are normally raised implicitly by HW or SW conditions 4/23/2018 Assoc. Prof. Stoyan Bonev
27
Assoc. Prof. Stoyan Bonev
EH in BASIC UNStructured Exception Handling - unSEH On Error GoTo <lab> Resume Next On Error GoTo 0 Resume On Error Resume Next Resume <lab> Structured Exception Handling – SEH try catch finally 4/23/2018 Assoc. Prof. Stoyan Bonev
28
Assoc. Prof. Stoyan Bonev
EH in BASIC – 2 stmts On Error - How to transfer control for EH process? Branch to Ehandler code On Error GoTo <lab> Suppress the error handling On Error GoTo 0 Ignore the exception, skip the stmt that caused the exception and branch to next stmt that follows On Error Resume Next 4/23/2018 Assoc. Prof. Stoyan Bonev
29
Assoc. Prof. Stoyan Bonev
EH in BASIC – 2 stmts Resume - How to continue after EH processing? Continue with stmt that follows stmt that caused the exception Resume Next Return to the stmt that raised the exception Resume Control is transferred to the stmt labeled <lab> Resume <lab> 4/23/2018 Assoc. Prof. Stoyan Bonev
30
Assoc. Prof. Stoyan Bonev
Unstructured EH A run-time error is one that occurs when using your application. Consider the following application: 4/23/2018 Assoc. Prof. Stoyan Bonev
31
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 Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice End Sub 4/23/2018 Assoc. Prof. Stoyan Bonev
32
Assoc. Prof. Stoyan Bonev
Here is an example of executing it: 4/23/2018 Assoc. Prof. Stoyan Bonev
33
Detailed Design Process
The first aspect you should take into consider is to imagine what could cause a problem. If you think there is such a possibility, start by creating a label that could be used to transfer code if a problem occurs. Here is an example: 4/23/2018 Assoc. Prof. Stoyan Bonev
34
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 Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice ThereWasAProblem: End Sub 4/23/2018 Assoc. Prof. Stoyan Bonev
35
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 Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice ThereWasAProblem: MsgBox("There was a problem when executing your instructions") End Sub 4/23/2018 Assoc. Prof. Stoyan Bonev
36
Assoc. Prof. Stoyan Bonev
If you create such a label, you should tell the compiler when to jump to that label. Otherwise, as in this case, the label section would always execute. Here is an example of running the above version: 4/23/2018 Assoc. Prof. Stoyan Bonev
37
Assoc. Prof. Stoyan Bonev
4/23/2018 Assoc. Prof. Stoyan Bonev
38
Assoc. Prof. Stoyan Bonev
In this case, we want the label section to execute only when we want it to. To prevent the compiler from reaching this section if not directed so, you can add an Exit Sub line above the label section: 4/23/2018 Assoc. Prof. Stoyan Bonev
39
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 Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice Exit Sub ThereWasAProblem: MsgBox("There was a problem when executing your instructions") End Sub 4/23/2018 Assoc. Prof. Stoyan Bonev
40
Assoc. Prof. Stoyan Bonev
This time if you execute the program with an appropriate value, the label section would not be reached. 4/23/2018 Assoc. Prof. Stoyan Bonev
41
In Case Of Error, Jump To Label
.
42
Assoc. Prof. Stoyan Bonev
The above program will compile fine. When executing it, imagine that the user types an inappropriate value such as 24$.58 instead of (4,$ same keyboard button). In this case, the value is not a number, the program would "crash" and let you know that there was a problem: 4/23/2018 Assoc. Prof. Stoyan Bonev
43
Assoc. Prof. Stoyan Bonev
4/23/2018 Assoc. Prof. Stoyan Bonev
44
Assoc. Prof. Stoyan Bonev
With some experience, you would know what the problem was, otherwise, you would face a vague explanation. The short story is that the compiler couldn't continue because, in this case, it could not multiply 24$.58 by 2. If a problem occurs when a person is using your program, the compiler may display a nasty and insignificant message to the user who would not know what to do with it. Therefore, you can start by creating an appropriate label as introduced above. An error normally occurs in a procedure. Therefore, to make your code easier to read, you should create a label that shows that it is made for an error instead of being a regular label. The label should also reflect the name of the procedure. Here is an example: 4/23/2018 Assoc. Prof. Stoyan Bonev
45
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 Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice Exit Sub Button1_Click_Error: MsgBox("The operation could not be executed", MsgBoxStyle.OKOnly, "Operation Error") End Sub 4/23/2018 Assoc. Prof. Stoyan Bonev
46
Assoc. Prof. Stoyan Bonev
When you think there will be a problem in your code, somewhere in the lines under the name of the procedure but before the line that could cause the problem, type On Error GoTo followed by the name of the label that would deal with the error. Here is an example: 4/23/2018 Assoc. Prof. Stoyan Bonev
47
Assoc. Prof. Stoyan Bonev
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click On Error GoTo Button1_Click_Error Dim Number As Double Dim Twice As Double Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice Exit Sub Button1_Click_Error: MsgBox("The operation could not be executed", MsgBoxStyle.OKOnly, "Operation Error") End Sub 4/23/2018 Assoc. Prof. Stoyan Bonev
48
Assoc. Prof. Stoyan Bonev
Here is an example of running the program: 4/23/2018 Assoc. Prof. Stoyan Bonev
49
Assoc. Prof. Stoyan Bonev
When the On Error GoTo statement is used, this indicates to the compiler that if any type of error occurs while the code of this procedure is executed, transfer the control to the label. In this case, as soon as something bad happens, the compiler marks the area where the problem occurred, skips the normal code and jumps to the label indicated by the On Error GoTo line. After the section of that label is executed, the compiler returns where the error occurred. If there is nothing to solve the problem, the compiler continues down but without executing the lines of code involved. In this case, it would encounter the Exit Sub line and get out of the procedure. 4/23/2018 Assoc. Prof. Stoyan Bonev
50
Resume .
51
Assoc. Prof. Stoyan Bonev
If a problem occurs in your code and you provide a label to display a friendly message as done above, the compiler would display the message and exit from the procedure. If this happens, as mentioned above, when the compiler returns where the problem occurred, you can provide an alternate program reaction. For example, in our program, if the user provides an inappropriate value that causes the error, you can provide an alternate value and ask the compiler to continue as if nothing happened. In this case, you want the compiler to "resume" its activity. 4/23/2018 Assoc. Prof. Stoyan Bonev
52
Assoc. Prof. Stoyan Bonev
To indicate that the program should continue, you can use the Resume keyword. Here is an example: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click On Error GoTo Button1_Click_Error Dim Number As Double Dim Twice As Double Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice Exit Sub Button1_Click_Error: MsgBox("The operation could not be executed", MsgBoxStyle.OKOnly, "Operation Error") Resume End Sub 4/23/2018 Assoc. Prof. Stoyan Bonev
53
Assoc. Prof. Stoyan Bonev
When an error occurs, if you want the program to continue with an alternate value than the one that caused the problem, in the label section, type Resume Next. Here is an example: 4/23/2018 Assoc. Prof. Stoyan Bonev
54
Assoc. Prof. Stoyan Bonev
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click On Error GoTo Button1_Click_Error Dim Number As Double Dim Twice As Double Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice Exit Sub Button1_Click_Error: MsgBox("The operation could not be executed“, MsgBoxStyle.OKOnly, "Operation Error") Resume Next End Sub 4/23/2018 Assoc. Prof. Stoyan Bonev
55
Assoc. Prof. Stoyan Bonev
In this case, since any numeric variable is initialized with 0, when the compiler returns to the line of code that caused the problem, it would use 0 as a substitute to the inappropriate value. Based on this, you can provide a new value to use in case of error. Here is an example: 4/23/2018 Assoc. Prof. Stoyan Bonev
56
Assoc. Prof. Stoyan Bonev
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click On Error GoTo Button1_Click_Error Dim Number As Double Dim Twice As Double Number = Me.TextBox1.Text Twice = Number * 2 Me.TextBox2.Text = Twice Exit Sub Button1_Click_Error: MsgBox("The operation could not execute" &VbCrLf & _ “10 will be used ”,MsgBoxStyle.OKOnly,"Operation Error") Number = 10 Resume Next End Sub 4/23/2018 Assoc. Prof. Stoyan Bonev
57
Here is one example of running the program:
4/23/2018 Assoc. Prof. Stoyan Bonev
58
Here is another example of running the same program:
4/23/2018 Assoc. Prof. Stoyan Bonev
59
Assoc. Prof. Stoyan Bonev
EH in Pascal {$I-} (* suppress system reaction *) readln(x); {$I+} (* restore system reaction *) IF IOResult<>0 then begin writeln(‘IO Error …’); halt; end; 4/23/2018 Assoc. Prof. Stoyan Bonev
60
Assoc. Prof. Stoyan Bonev
EH in C EH based on test values returned by RTL functions in = fopen(“IN.TXT”, “rt”); if ((in = fopen(“IN.TXT”, “rt”))==NULL) { printf(“Can’t open file”); exit(1); } 4/23/2018 Assoc. Prof. Stoyan Bonev
61
Assoc. Prof. Stoyan Bonev
EH in Ada begin { the block of unit body } exception when exception1 => first handler when exception2 => second handler other handlers end 4/23/2018 Assoc. Prof. Stoyan Bonev
62
Assoc. Prof. Stoyan Bonev
EH in C++, Java, C# EH is based on a special construct named try to specify the scope of exception handlers A try construct includes: compound stmt called try clause; a list of exception handlers. The compound statement defines the scope of the following handlers. 4/23/2018 Assoc. Prof. Stoyan Bonev
63
Assoc. Prof. Stoyan Bonev
try { // code expected to raise an exception } catch(<formal parameter>) { … // code – EHandler body … 4/23/2018 Assoc. Prof. Stoyan Bonev
64
Assoc. Prof. Stoyan Bonev
All the catch functions are EHandlers. A catch function can have only a single parameter which is similar to functions in C/C++. The formal parameter can be naked type specifier or a type specifier followed by a variable name. When information about exception is to be passed to the EHandler, the parameter includes var name. Otherwise the formal parameter can be just a type name, whose only purpose is to make the EHandler uniquely identifiable. 4/23/2018 Assoc. Prof. Stoyan Bonev
65
Bringing (binding) exceptions to EHandlers
C++ exceptions are raised only by the explicit statement throw, whose general syntax form is: throw <expression>; throw; The type of throw expression selects the particular EHandler, with matching type formal parameter. Throw without an operand can only appear in a EHandler and it re-raises the exception which is then handled elsewhere. 4/23/2018 Assoc. Prof. Stoyan Bonev
66
Continuation after EH execution
After an EHandler has completed its execution, control flows to the first statement following the try construct. If no EHandler match is found locally, the exception is propagated to the caller of the function in which it was re-raised. If no matching handler is found in the program, the program is terminated. 4/23/2018 Assoc. Prof. Stoyan Bonev
67
Assoc. Prof. Stoyan Bonev
Examples with EH in C++ Demo program: Source text: SBExcept1.cpp Executable code: SBExcept1.exe 4/23/2018 Assoc. Prof. Stoyan Bonev
68
Assoc. Prof. Stoyan Bonev
SBExcept1 The program produces accumulated sum of integer values entered from the keyboard Endless loop to accumulate sum of integer values Input stream is terminated by EOD, registered and used to throw exception See handout or next slide // Exception handler for end of input data condition // Exception handler catch(short int) - only type specifier 4/23/2018 Assoc. Prof. Stoyan Bonev
69
Assoc. Prof. Stoyan Bonev
#include <iostream> using namespace std; void main() { int val, sum = 0; short int eofcondition=-55; try { cout << "\n Enter integer value:"; while( 1 ) { if ( !(cin >> val) ) throw eofcondition; sum = sum + val; cout << "\n\n Enter new integer value or CTRL/Z to end:"; } } catch (short int) // handler for end of input data // only type specifier { cout << "\n END OF INPUT DATA ENCOUNTERED"; cout << "\n\n Total sum accumulated is " << sum; } system ("pause"); } 4/23/2018 Assoc. Prof. Stoyan Bonev
70
Assoc. Prof. Stoyan Bonev
Examples with EH in C++ Demo program: Source text: SBExcept2.cpp see handout page 2 Executable code: SBExcept2.exe 4/23/2018 Assoc. Prof. Stoyan Bonev
71
Assoc. Prof. Stoyan Bonev
SBExcept2 The program accumulates three sums of integer values // Exception handler for end of input data condition // Exception handler catch(short int) - only type specifier // Exception handler value in the range // typical value of 22 // Exception handler catch(int valparam) - type and variable name // sum1 accumulates sum of all values // sum2 accumulates sum of values in the range // sum3 accumulates only the value of 22 4/23/2018 Assoc. Prof. Stoyan Bonev
72
Assoc. Prof. Stoyan Bonev
void main() { int val, sum1 = 0, sum2 = 0, sum3 = 0; short int eofcondition = 0; try { cout << "\n Enter integer value:"; while( 1 ) { if ( !(cin >> val) ) throw eofcondition; { // inner try construct if ( val>=20 && val<= 100 ) throw(val); } catch (int valparam) sum2 = sum2 + valparam; if (valparam==22) sum3 = sum3 + valparam; } // end of inner try construct sum1 = sum1 + val; cout << "\n\n Enter new integer value or CTRL/Z to end:"; catch (short int) // handler for end of input data, only type specifier { cout << "\n\n Total sum accumulated is " << sum1; cout << "\n\n Totall sum of values in range is "<< sum2; cout << "\n\n Total sum of values 22 is " << sum3; 4/23/2018 Assoc. Prof. Stoyan Bonev
73
Assoc. Prof. Stoyan Bonev
Examples with EH in C++ Demo program: Source text: SBExcept3.cpp Executable code: SBExcept3.exe 4/23/2018 Assoc. Prof. Stoyan Bonev
74
Assoc. Prof. Stoyan Bonev
SBExcept3 The program counts how many times the values of 0, 1, 2, … , 19 appear in the input stream // Exception handler for end of input data condition // Exception handler catch(short int) - only type specifier // Exception handler array subscript range // array pom[20] subscript range is // Exception handler catch(int valparam) - type and var name // each correct subscript value // is to be correspondingly accumulated pom[val]++; 4/23/2018 Assoc. Prof. Stoyan Bonev
75
Assoc. Prof. Stoyan Bonev
void main() { int val, pom[20]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; short int eofcondition=-55; try { cout << "\n Enter integer value:"; while( 1 ) { if ( !(cin >> val) ) throw eofcondition; { // inner try construct try { if ( val<0 || val>19) throw(val); pom[val] ++; } catch (int valparam) cout << "\n\n Array subscript range exception raised"; cout << "\n You entered value " << valparam << " which is not in range "; cout << "\n The value you entered is ignored"; } // end of inner try construct cout << "\n\n Enter new integer value or CTRL/Z to end:"; catch (short int) // handler for end of input data, only type specifier { cout << "\n Total result of input data\n"; int i; for (i=0; i<=19; i++) cout << pom[i]<< " "; 4/23/2018 Assoc. Prof. Stoyan Bonev
76
Assoc. Prof. Stoyan Bonev
Examples with EH in C++ Demo program: Source text: SebestaExcept.cpp Executable code: SebestaExcept.exe 4/23/2018 Assoc. Prof. Stoyan Bonev
77
Assoc. Prof. Stoyan Bonev
SebestaExcept The program produces a distribution of input grades by using an array of counters for 10 categories (0-10, 11-20, … 81-90, ). Illegal grades are detected by checking for invalid subscripts in incrementing the selected counter freq[index]++; Two exceptions are used: to handle EOD condition to handle index value in range 0..9 4/23/2018 Assoc. Prof. Stoyan Bonev
78
Assoc. Prof. Stoyan Bonev
void main(){ int new_grade, index, limit_1, limit_2, freq[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; short int eof_condition=-55; try { while (1) { new_grade = 400; if (!(cin >> new_grade)) throw eof_condition; // cin detects eof index = new_grade/10; { try { if (index<0 || index>9) throw (new_grade); freq[index]++; } catch(int grade) // handler of index errors if (grade==100) freq[9]++; else cout <<"\nError-new grade "<<grade<< " is out of range"; } // end of inner try compound } // end of while(1) } // end of outer try compound catch(short int) // handler for eof condition { cout << "\n\n\nFrom\tTo\tFrequence"; cout << "\n========================="; for (index=0; index<10; index++) {limit_1=10*index; limit_2 = limit_1 +9; if(index==9) limit_2 = 100; cout << "\n"<<limit_1<<"\t"<<limit_2<<"\t"<<freq[index]; } // end of this catch } // end of main 4/23/2018 Assoc. Prof. Stoyan Bonev
79
Assoc. Prof. Stoyan Bonev
Examples with EH in C++ Demo program: Source text: SBExcept4.cpp Executable code: SBExcept4.exe 4/23/2018 Assoc. Prof. Stoyan Bonev
80
Assoc. Prof. Stoyan Bonev
SBExcept4 The program reads the input stream and each recognized lower case letter is converted to upper case. // Exception handler for end of input data condition // Exception handler catch(short int) - only type specifier // Exception handler input char is not lowercase letter 'a‘..'z' // EHandler catch (char val1param) - type and var name // val1 stores the entered character // val2 stores the converted character or // in case of invalid conversion 4/23/2018 Assoc. Prof. Stoyan Bonev
81
Assoc. Prof. Stoyan Bonev
void main() { char val1, val2; short int eofcondition=-55; try { cout << "\n Enter character value:"; while( 1 ) { if ( !(cin >> val1) ) throw eofcondition; { // inner try construct try { if (val1<'a' || val1>'z') throw(val1); val2 = val1 - ('a' - 'A'); // lower case to upper case } catch (char val1param) cout << "\n\nYou entered the '"<<val1param<< "' that can't be converted to upper case letter"; cout << "\nCharacter replaced with val2 = } // end of inner try construct cout << "\nEntered char:”<<val1<<” Converted char:“<< val2; catch (short int) // handler for end of input data, only type specifier cout << "\n END OF INPUT DATA ENCOUNTERED"; 4/23/2018 Assoc. Prof. Stoyan Bonev
82
Reminder: Quiz 4 on EH to come next class
83
Exception Handling and Event Handling
Chapter 14 Exception Handling and Event Handling Source: Longman dictionary 1987 83
84
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-84 Source: Longman dictionary 1987 84
85
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-85 Source: Longman dictionary 1987 85
86
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-86 Source: Longman dictionary 1987 86
87
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-87 Source: Longman dictionary 1987 87
88
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-88 Source: Longman dictionary 1987 88
89
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-89 Source: Longman dictionary 1987 89
90
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-90 Source: Longman dictionary 1987 90
91
Exception Handling Control Flow
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 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-92 Source: Longman dictionary 1987 92
93
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-93 Source: Longman dictionary 1987 93
94
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-94 Source: Longman dictionary 1987 94
95
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-95 Source: Longman dictionary 1987 95
96
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-96 Source: Longman dictionary 1987 96
97
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-97 Source: Longman dictionary 1987 97
98
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-98 Source: Longman dictionary 1987 98
99
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-99 Source: Longman dictionary 1987 99
100
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-100 Source: Longman dictionary 1987 100
101
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-101 Source: Longman dictionary 1987 101
102
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-102 Source: Longman dictionary 1987 102
103
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-103 Source: Longman dictionary 1987 103
104
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-104 Source: Longman dictionary 1987 104
105
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-105 Source: Longman dictionary 1987 105
106
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-106 Source: Longman dictionary 1987 106
107
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-107 Source: Longman dictionary 1987 107
108
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-108 Source: Longman dictionary 1987 108
109
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-109 Source: Longman dictionary 1987 109
110
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-110 Source: Longman dictionary 1987 110
111
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-111 Source: Longman dictionary 1987 111
112
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-112 Source: Longman dictionary 1987 112
113
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-113 Source: Longman dictionary 1987 113
114
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-114 Source: Longman dictionary 1987 114
115
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-115 Source: Longman dictionary 1987 115
116
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-116 Source: Longman dictionary 1987 116
117
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-117 Source: Longman dictionary 1987 117
118
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-118 Source: Longman dictionary 1987 118
119
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-119 Source: Longman dictionary 1987 119
120
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-120 Source: Longman dictionary 1987 120
121
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-121 Source: Longman dictionary 1987 121
122
Thank You For Your Attention
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.