Download Program Robustness And Exception Handling-Aeronautical Engineering And Computer Programming-Lecture Slides and more Slides Aeronautical Engineering in PDF only on Docsity!
3
Today
4
Internet
computers running versions of Berkeley UNIX, and
used their resources to attack still more computers.
across the U.S., infecting thousands of computers
and making many of them unusable due to the
burden of its activity.
- Cause : undetected buffer overflow in C routine
gets()
• Program robustness
• Exception handling
November 2, 1988 Internet Worm
A self-replicating program was released upon the
This program (a worm) invaded VAX and Sun
Within the space of hours this program had spread
5
several patients
- Cause : poor testing of the software
• st
communicating with NASA
- Cause : Approach orbit angle was incorrect because
of inconsistency between units of measurement
7
Errors
– Exceptions
1986: Therac 25 radiation machine kills
June 4, 1996: 1 flight of Ariane 5 aborted:
Ariane 5 destroyed
: Code from Ariane 4 guidance system was
reused in Ariane 5 but not tested.
September 23 1999: Mars Orbiter stops
• No programmer is perfect
– The good ones handle errors gracefully
• Errors
– Compile time
– Link-time
• Run-time errors
– Program errors
User errors
10
Robustness
without either
11
Finding Errors
• Your program should never terminate
– Completing successfully
– Sending a meaningful error message
• Approaches to achieve Robustness
– Debug
– Defensive programming
- Conditional checks
- Assertions
– Exception handling
• Try to “break” the program
– What can go wrong?
– What happens if it does?
– Sometimes nothing needs to be done.
– If that is a problem, how can we detect it?
– What can we do about it?
- Tell the user
- Die gracefully
- Recover reasonably
12
Ada’s Classification of Errors 1.1.
required to be
detected prior to run time by every
Ada implementation
required to be
detected at run time by the execution
of an Ada program
13
exception represents a kind of
exceptional situation
time) is called:
raise an exception is to abandon
normal program execution
the arising of an exception is called
handling the exception
1. Errors that are
2. Errors that are
3. Bounded errors
4. Erroneous execution
Exceptions – Ada Perspective
• An
– An occurrence of such a situation (at run
exception occurrence
• To
• Performing some actions in response to
17
16
Exception Handlers
is specified by an exception_handler
subprogram specification
declarations
begin
statements
exception
one or more exception handlers
end;
Exception Handling
for that exception
terminates
- never returns to point where exception
occurred
passed back to its caller
- main reached with no handler
(program crashes)
- (^) subprogram specification declarations begin statements exception one or more exception handlers end;
• The response to one or more exceptions
• Operation:
When exception occurs, control jumps to the handler
When handler statements finish, subprogram
Control
If no handler, subprogram terminates and exception is
Keep doing this until
Or suitable handler found
18
Example
with Ada.Text_IO; use Ada.Text_IO;
procedure Open_File is
Filename : String (1 .. 30); Namelen : Natural; The_File : File_Type;
begin
Put (“What file do you want to read? "); Get_Line (Filename, Namelen); Open (File => The_File, Name => Filename (1 .. Namelen), Mode => In_File);
exception when Status_Error => Put_Line ("The file is already open"); when Name_Error => Put_Line ("There is no file with that name"); when Use_Error => Put_Line ("The file cannot be read"); when others => Put_Line ("Unexpected error on opening file"); end Open_File;
19
Raise Statements
– raise exception_name;
– raise; --re-raise the current exception
• A raise_statement raises an exception
22
Exception in block statements
statement is to
handling (especially in a loop).
appropriate exception handler
23
Example program
--Safe I/O with Ada.Text_Io; use Ada.Text_Io;
procedure Ex2 is type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun); package Day_Io is new Enumeration_Io (Days); use Day_Io; Local_Day : Days; --entered by user Good_Day : Boolean := False; --loop control
begin
while not Good_Day loop begin Put ("Enter a day name (first 3 letters) : "); Get (Local_Day);
Good_Day := True;
exception when Data_Error => Put ("Must be first 3 letters of a day name"); New_Line; Skip_Line; end; end loop; Skip_Line; end Ex2;
Block
• The other reason for defining a block
enable local exception
• Operation:
– when an exception occurs:
- execution transfers straight to its exception handler
- appropriate exception handler is executed
- execution of the whole block statement terminates
- execution continues with statement after the block
– if no local exception handler:
- block terminates immediately
- control passes to outer block, to see if it has an
- etc.
-- this point is only reached if valid entry given
-- exception handler for while block
24
Strategies for handling
exceptions
detect, identify, pass it on
program halts (crashes)
25
1. Take control
• Example : tan(x) may be impossible to compute or
represent
handled
anything was wrong.
function Tan (X : Float )
return Float is
begin
return Sin(X) / Cos(X);
exception
when Constraint_Error =>
if (Sin(X)>=0.0 and Cos(X)>= 0.0) or
(Sin(X)< 0.0 and Cos(X)< 0.0)
then
return Float'Last;
else
return -Float'Last;
end Tan;
Three levels of ambition:
1. Take control
try to act so program can continue
2. Identify exception for handling elsewhere
3. Ignore
Constraint_Error exception can be detected and
Handle the exception locally; caller never realizes
end if
Exceptions in Input/Output A.
• TEXT_IO defines several exceptions:
Exception Example
data_error invalid data type, data has wrong form
status_error try to open an already open file
mode_error try to read from an output file
name_error no such file
use_error try to open printer for reading
end_error EOF encountered while reading
layout_error SET_COL beyond LINELENGTH limit
device_error hardware failure
29
Reading enumeration values
--Safe I/O (again) type Days is function Get_Day return Days is Local_Day : Days; Good_Day : Boolean := False: begin while not Good_Day loop begin Put ("Enter a day name (first 3 letters) : "); Get (Local_Day);
Good_Day := True; exception when Data_Error => Put ("Must be first 3 letters of a day name"); New_Line; Skip_Line; end; end loop; Skip_Line; return Local_Day; end Get_Day;
(Mon, Tue, Wed, Thu, Fri, Sat, Sun);
-- entered by user -- loop control
-- while block
-- this point only reached if valid entry given
-- exception handler for while block
-- while block
28
30
Reading enumeration values, with range checks
type Week_Days is (Sun, Mon, Tue, Wed, Thu, Fri, Sat);
subtype Work_Days is Week_Days range Mon .. Fri;
subtype Weekend_Days is Week_Days range Sat .. Sun;
procedure Safe_Get_Day (
Out_Day : out Week_Days;
Min : in Week_Days := Work_Days'First;
Max : in Week_Days := Work_Days'Last ) is
Local_Day : Week_Days;
Good_Day : Boolean := False;
31
begin Good_Day loop begin Put("Enter an day between "); Put( Min ); Put(" and "); Put( Max ); Put(" "); Get( Local_Day );
if (Local_Day < Min) or (Local_Day > Max) then raise Data_Error; else Good_Day := True; ;
exception when Data_Error => Put_Line("Invalid day!. Good days are "); for This_Day in Week_Days range Min .. Max loop Put( This_Day ); Put(" "); ; New_Line; Skip_Line; end; ;
Skip_Line; Out_Day := Local_Day; end Safe_Get_Day;
-- procedure for the safe input of enumeration values
-- local input var
-- loop control
-- safe_get_day while not -- while block
-- this point is reached only when input is a day code
end if -- this point is reached if input is a valid day code -- between min and max
end loop -- tidy up terminal -- protected while block end loop -- this point can only be reached when valid value input -- tidy up terminal handling -- export input value
34
Opening a file
procedure Open_File (The_File : File_Type ) is
Filename : String (1 .. 30);
Namelen : Natural;
begin
Put ("What file do you want to read? ");
Get_Line (Filename, Namelen);
Open (File => The_File, Name => Filename (1 .. Namelen),
Mode => In_File);
exception
when Status_Error =>
Put_Line ("The file is already open");
when Name_Error =>
Put_Line ("There is no file with that name");
when Use_Error =>
Put_Line ("The file cannot be read");
Put_Line ("Unexpected error on opening file");
end Open_File;
35
User defined exceptions 1(4)
Tan_Error : exception;
Example:
procedure Main is X, Res : Float; Tan_Error : exception; function Tan (X : Float ) return Float is begin return Sin(X)/Cos(X); exception when Numeric_Error => raise Tan_Error; end; begin Put (“Enter A Real Number X: “); Get (X);
Put (“Tan(X) is “); Put(Res); New_Line; exception when Tan_Error =>
end;
-- safe file opening
in out
when others
• You can declare your own exception types
Res := Tan(X);
Put_Line (“The Tangent is Too Big”);
36
Declaring exceptions in
packages
prefer to pass an exception back to the caller.
too general
- best is in a package , along with TAN
37
Example
--package specification
package TRIGONOMETRY is
function SIN (X : FLOAT) return FLOAT;
function COS (X : FLOAT) return FLOAT;
function TAN (X : FLOAT) return FLOAT;
TAN_ERROR : exception;
end TRIGONOMETRY;
--package body
package body TRIGONOMETRY is
function SIN (X : FLOAT) return FLOAT is
begin ... end SIN;
function COS (X : FLOAT) return FLOAT is
begin ... end COS;
function TAN (X : FLOAT) return FLOAT is
begin return SIN(X) / COS(X);
exception
end TAN;
end TRIGONOMETRY;
Shows how a package
specification can define an
exception; the package body
can raise that exception when
appropriate; and a user program
can recognize and handle the
exception
NUMERIC_ERROR may arise in tan(x) function
Perhaps too unilateral to handle it locally, so
What to pass back?
more specific name (eg TAN_ERROR)
Where to declare TAN_ERROR?
not in function TAN (invisible outside)
not in calling code (belongs with TAN)
when NUMERIC_ERROR => raise TAN_ERROR