1 exceptions & exception handling mechanisms. 2 exceptions definition declaration nature of...
Post on 27-Dec-2015
278 Views
Preview:
TRANSCRIPT
3
Exceptions Definition
Exceptions are unusual events or error conditions that occur during run time
Such an event will result in a change of normal control flow.
E.g. Failing to dial a prefix 9 in IIT telephone network while calling a number outside the IIT network.
4
Exceptions
What events are unusual depends on the application and the situation that leads to those events
An exception in one case may not be so in another
E.g. Dialing prefix 9 in a telephone that is outside the IIT network.
5
Exceptions The severity of an exception also
depends mostly on the application under consideration and the situation in which the exception has occurred. E.g.
A wrong number in a telephone application will result only in a wrong call being placed.
But a wrong number in a life support system controller may end up fatal.
6
Exceptions
So, exact list of exceptions for an
application is defined by the developer
that decision will be based on the application under consideration.
7
Exception Declaration As any other object in the software
paradigm there should be a way to represent exceptions
This has some important objectives, Exceptions should be made explicit to the
programmers so that they can consciously and cleverly utilize them in building robust applications.
The compiler will be able to aid the developers in various ways once they understand the exception objects, their type, binding, scope etc.
8
Exception declaration To help programmers as we have
mentioned above we need the following, at least. Give each instance of each exception type a
unique identification. Once the exception has been identified, we
need additional information about the cause of that exception
The requirements are not limited to just the list here.
9
Exception declaration Exceptions are being represented
in different ways. A few popular examples are, Return value and flags UNIX signals Objects in OOP languages
We will examine each one of these mechanisms later in this presentation.
10
Nature of exceptions Exception can be classified as
synchronous asynchronous user unaware
The above classification is from the aspect of the developer so that we can estimate how well one can be prepared to handle exceptions of the above categories.
11
Nature of exceptions
The synchronous ones are those that occur because of the actions of the execution in which they occur.
The executions are responsible for the exceptions that they have to face. E.g. try-catch mechanism, return value
indication.
12
Nature of exceptions Asynchronous ones are those that occur
in an execution different from the one where the exception is present. This occurs because of something not done by the execution that gets the exception. The exception is then propagated to the destination exception where it will be handled.
E.g. One thread stopping another thread using the signal mechanism
13
Nature of exceptions User unaware exceptions:
A method calling another will not be aware of all the exceptions that could be thrown by the called method.
This problem plagued C++. E.g.
If a developer has to use a class developed by someone else, he may not always have access to the source code.
All the developer can have for sure is the interface of that class. So there is no practical way he or the compiler can check and handle the exceptions thrown by that class or by another class used in that class.
14
Exception Handling Mechanisms
Exception Handling Mechanism Purpose Definition (What is EHM?) Declaration Nature of exception handling
15
Exception Handling Mechanism
Why do we need exceptions and exception handling mechanism Unusual events or errors are not uncommon in
software products. We have exceptions to address such events. Having identified exceptions we need a way to
process them. The mechanism to process such exception
events is called as Exception Handling Mechanism
16
Exception Handling Mechanisms
Exception handling is a programming language facility for the programmer to specify how an exception should be handled. E.g.
try-catch mechanism in Java Signal mechanism in Unix
17
Exception Handling Mechanisms
They (Exception Handlers) process the exceptions trying to recover from the error condition or to terminate in the best possible way. Best possible way implies “minimal
damage” to the state of the system under consideration.
Preserving the state variables
18
Exception Handling Mechanisms
The importance of EHM will be best understood by looking at the impact of a EHM on the resulting software products,
A poor exception handling mechanism might result in many or all of the following situations. Reliability? Stability? Defining new exceptions?
19
Code Tangling (Actual code and exception code)
Indecipherable code Finding and fixing bugs will be difficult Reverse engineering - a Herculean task. Adding new software modules Modifying existing software modules Might result in code
redundancy/duplication, if the same exception needs to be handled in
the same way in different parts of the program.
20
Nature of exception handling
Having discussed about the purpose and importance of exception handling, let us look at the choices we have in exception handling. 1) Termination 2) Retry 3) Resume
21
Termination. First popular mechanism The code after that point, at which an
exception occurs, will not be executed. i.e. the execution is terminated at the point
at which an exception occurs Once everything is done, in ideal case it
will look as if the execution terminated normally just before the exception point as if the exception never occurred
22
Termination.
Exception
Control Transfer 1
Control Transfer 2
This part of the code is
skipped
Termination ModelActual Program
BlocksCorresponding Exception
Handler Blocks
23
Termination example
try { buf = new char[512];
if( buf == 0 )
throw "Memory allocation failure!";
strycpy (buf, “This is a Test String”); } catch( char * str ) {
cout << "Exception raised: " << str << '\n'; }
Exception
Control Transfer 1
Control Transfer 2
This part of the code is
skipped
Termination ModelActual Program
BlocksCorresponding Exception
Handler Blocks
24
Retry Model
In this model, the handler will try to clean up the environment resulted from the exception and will try to restart the execution.
The original environment at that point of execution should be restored. This includes all the status flags,
program counter etc.
25
Retry Model
So the environment should be stored each time the execution crosses a restart point, irrespective of whether there will be an exception or not.
This is obviously an additional overhead (this was not there in termination model)
26
Retry Model
Exception
Control Transfer 1
ControlTransfer 2
Retry ModelActual Program
BlocksCorresponding Exception
Handler Blocks
Restart point
This part of the code will be executed
again
27
Retry model – restart point
Care should be taken while deciding the restart points.
If chosen too closely the overhead of saving the environment will be high.
If chosen too sparsely, when restarted from an exception too much of code will be repeated possibly resulting in more damage (like many files could have been changed etc) and poor performance.
28
Retry model – restart point In general the starting point of a guarded
block will serve as the restart point It could be logical too, depending on the
application under consideration. E.g. A bank may want to restart from a point
where processing a record starts. This makes sense because starting somewhere else will result in partial processing of a record (if a new record is fetched to restart) or doing some part of the processing for a particular record twice (if the same record is used to restart).
29
Retry model – E.g. using return value mechanism
main(int argc, char **argv) { … int retry_count = MAX_RETRY; while ( retry_count- -) {
if ((hp = gethostbyname(hostname)) == 0) { perror("gethostbyname");
continue; } /* fill in the socket structure with host information */ … if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); continue; } /* connect to PORT on HOST */
if (connect(sd,(struct sockaddr *) &pin, sizeof(pin)) == -1) { perror("connect");
close(sd); continue; } } //while if (! retry_count) exit(1);}//main
30
Resumption Model
The handler does the work of cleaning up the damage resulted because of the exception
Then control is transferred to the point next to the one where the execution flow was interrupted because of the exception and the execution continues from there on.
31
Resumption Model
the environment should be saved so that when the handler is done with its job, the control can be returned back to the point where the exception occurred.
When the control is returned a clean environment will be provided using the saved copy.
32
Resumption Model
Exception
Control Transfer 1
ControlTransfer 2
Resumption ModelActual Program
BlocksCorresponding Exception
Handler Blocks
Exception point and restart
point
33
Resumption Model
One can say that the resume model is nothing but the retry model the retry point is each line of code in
the execution i.e. after executing each line the
environment should be saved
34
Resumption model – E.g. using return value mechanismmain(int argc, char **argv) { … int retry_count = MAX_RETRY; while ( retry_count- -) {
if ((hp = gethostbyname(hostname)) == 0) { perror("gethostbyname");
continue; } /* fill in the socket structure with host information */ } //while … while ( retry_count- -) { if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); continue; } /* connect to PORT on HOST */ } //while while ( retry_count- -) { if (connect(sd,(struct sockaddr *) &pin, sizeof(pin)) == -1) { perror("connect"); sleep(17); continue; } } //while if (! retry_count) {close(sd); exit(1);}}//main`
35
Resumption Model Though resume seems to be the
best solution at hand, there are limitations. It does not resume exactly restoring everything. E.g. if the source execution had
incremented a counter in a file and while closing the file encountered an exception. The handler will not have enough knowledge to restore the counter in the file
36
Resumption Model
Things like this cannot be fixed and might result in fatal damages depending on the situation.
Thus we can say that the EHM does not guarantee a complete recovery from an exception. It merely attempts to minimize the damage
37
Propagation mechanism Responsible for delivering the
exception to the correct handler The propagation execution can be
different from the source execution and the faulting execution
OR one of those two (source / faulting) can have the propagation functionality in itself.
38
Propagation mechanism
In order to deliver the exceptions at the correct destination, the propagation mechanism sometimes has additional work E.g. Unwinding the stack while
navigating up in the function call tree in try-catch mechanism
39
Propagation mechanism
Propagation mechanism can be one of the following, Static Dynamic
This classification is based on the way the destination is chosen by the propagation mechanism.
40
Static propagation
In Static propagation the handler that will be used in a particular case will be known during compile time
A sequel has routines associated with it.
Exceptions are defined as sequels. When an exception is raised the sequel used to indicate that exception is called.
41
Static propagation
This sequel is hard coded and the exception handler is available during compile time.
The sequel proposed by Tennent is an example of static propagation.
42
Static propagation - example
class stack { stack( sequel overflow(...) ) { ... } void push( int i ) { ... raise overflow(...); }};
{ sequel StackOverflow(...) { ... } stack s( StackOverflow ); ... s.push( 3 ); // causes overflow}
The handler routine is
passed as a parameter to
the constructor
Exception Handler
routine in this case
43
Dynamic propagation The propagation model decides the
handler to which the exception should be delivered.
The decision is made at run-time. The decision usually depends on
the type of exception thrown. Most widely used E.g. Java try-catch mechanism
44
Dynamic propagationclass stack{ stack() { ... } void push( int i ) { ...
throw overflowexception;
...throw generalStackException;
}};try{ stack s(); ... s.push( 3 ); // causes overflow}catch (OverflowException e ){
//handler1}catch(OtherStackException e){//handler2 }
Handlers chosen
depending on the
exception
45
EXISTING EXCEPTION HANDLING MECHANISMS
Some of the today’s popular Exception Handling mechanisms, Return value and flags UNIX signal mechanism Object oriented mechanism
46
Return value and flags oldest exceptions handling mechanisms still in use exceptions are represented as numbers value of the number decides the type of
exception numbers are usually return values of
procedures.
47
Return value and flags
When procedures return control back to the caller they indicate any exception that may have occurred using the appropriate return values
The caller then checks the return value looking for any possible exceptions.
48
Return value and flags
In case of flags, a flag is set to indicate error or
exception. The handler code is executed if a flag
is set. This is found by checking the flag bit
whenever required.
49
Return value and flags
Problem with this mechanism Multiple instances of an exception
cannot be thrown The second instance will overwrite the
first by setting the respective flag Numbers just convey the exception
type Does not carry any additional information
50
Return value and flags Exception code and actual code are
intermixed One should check for all errors
explicitly, a new error condition, requires changes in all calling programs.
All the developers will not have the same value for an exception i.e. no standard value for exception so not portable
51
Return value and flags - example
int main(int argc,char **argv) { int s; s = socket(PF_LOCAL,SOCK_DGRAM,0); if ( s == -1 ) {
fprintf(stderr,"%s:socket(PF_LOCAL,SOCK_DGRAM,0)\n",strerror(errno));
return -1; /* Failed */ } printf("s = %d;\n",s); return 0;}
52
Return value and flags-example
Here the exception checking code is intermixed with the actual code.
As the complexity increases it would be very difficult to reverse engineer the code and get the actual program logic
53
UNIX signal mechanism exceptions are represented as signals The signal doesn’t carry any additional
information Exception handling is done by the signal
handlers The handler can decide to terminate the
execution The control can be returned to a pre-
determined retry point using some of the C language constructs (e.g. far jump)
54
UNIX signal mechanism
The handler code in this case is separate from the actual code
Control is transferred to the handler code once the signal is received After executing the handler, the control
returns back to the actual code Actual code Handler Actual code
55
UNIX signal mechanism
The propagation mechanism here is responsible for delivering the signal In this case the signals are actually
software interrupts and hence the OS (operating system) takes care of delivering the signals.
56
UNIX signal mechanism Problems with this mechanism,
signals are again represented as numbers A pending signal is represented using a
single flag bit so could be over-written by another instance of
the same signal. Limited number of signals Each time after handling an exception, the
handler should be associated to that signal explicitly
57
UNIX signal mechanism
If different blocks have to handle the same exception with different handlers, the new signal-handler association will
replace the existing signal-handler association. The new handler should be good enough to call the first handler after completing its execution if both of them should be executed for an exception.
58
UNIX signal mechanism - example
// Exception Handler codevoid signal_handler(int dummy) {printf(“Arithmetic exception has occurred!\n”);exit(1);}// Program codeint main(){int i=10, j=5;// Register the handler signal(SIGFPE, signal_handler);
printf(“Valid operation 10/5 = %d\n”,i/j);
j=0;// Exception Divide-by-zeroprintf(“Invalid operation 10/0 = %d\n”,i/j); return 0;}}
Exception handler & program code –
separate
59
Object oriented mechanism exceptions are modeled as classes each instance represented as
objects of those classes exceptions as objects also carry
other information via its members. For instance in Java, the exceptions
can have a cause i.e. the exception that resulted in this exception thus creating a chain
60
Object oriented mechanism
Inheritance In Java, all the exceptions are
subclasses of the throwable class giving all the exceptions certain basic functionalities
A parent child hierarchy of exceptions is created
The hierarchy tree has made possible the standardization of the exceptions.
61
Object oriented mechanism the execution throwing the exception is
terminated OOP provides dynamic propagation
mechanism They locate the handler dynamically during
run-time depending on the exception thrown.
Stack is unwound until a matching handler is found
If no matching handler is found, usually the application will be terminated.
62
Object oriented mechanism Problems with this mechanism,
blocks of exception code and actual code are mixed up.
If the same handler is to be used in different places, code duplication is done
Adding new or changing existing exception handlers is difficult.
The try-catch mechanism requires the handlers in the order of the child-parent hierarchy.
63
Object oriented mechanism - examplepublic class EchoClient { public static void main(String[] args) throws IOException {
Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null;
try { echoSocket = new Socket("valkyrie", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: valkyrie."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: valkyrie."); System.exit(1); }…}
65
Feature Language Extension Feature
A collection of small program units, offering a complete logical functionality of the application.
The developer defines the boundary of a feature depending on the requirement.
Problem The above said Features interact i.e. modify each other’s
behavior Feature interaction results in dependencies between
modules. One has to implement changes in all the interacting features to modify one feature.
This means that developer of one module has to depend on the developer of the other if both modules interact. The dependencies will shoot up rapidly with the size/complexity of the application under consideration. Most of the real time systems have many features that highly interact with each other.
66
Feature Language Extension Impact of the problem in the software
Error prone since programmer is not most of the time sure if he has implemented the changes in all the required places.
Increasing cost for both development and maintenance
Because of this dependency of a feature on other features, it is not reusable.
There is no way one could analyze the features since the code for the features are tangled. i.e. they are not completely modularized as objects in OOP which would give us a better hold in automating the analysis of these software modules
67
Feature Language Extension FLE remedies the problem
FLE attempts to remedy the above said problems. We know that feature interaction is the root cause of this dependency and hence the issue. Thus FLE targets on that and has come up with an extension where we modularize the interacting features and provide them (features) a clean mechanism to interact with each other by sending messages. These messages in FLE terms are the events.
Thus FLE avoids the code tangling issue and hence gives a clean interface between features.
Given with a clean interface developers can work with pre-agreed interfaces and don’t have to depend on developers of other features as long as they stick to the agreed interface.
68
Feature Language Extension
FLE model FLE as the name says is an extension,
of Java and in turn OOP. One can visualize FLE as follows
Structured Programming
Object Oriented Programming
FLE Programming(feature oriented)
69
Feature Language Extension
In structured programming the data and functions that operated on the data were not closely coupled or bonded. One passes the data to the functions and get them worked on.
In OOP we have modularization, as in the methods which will work on the data enclose the data thus providing a module of data and related methods to users and is called an object
Feature language can be viewed one more level of modularization where we use the OOP’s classes/objects and build features these features interact with each other using events in the same way objects interact in java using messages.
Refer to figure in the next slide
71
Feature Language Extension FLE is non-procedural that it does not
specify the exact order of execution of the code.
Programmer first defines a model for his application and then works around that model
The model is composed of a domain statement
and a special feature called an anchor feature that implements the basic functionalities of a component.
72
Feature Language Extension
Other features are built around the anchor feature as an extension to the anchor feature.
Features are put together in feature packages
A feature package may be considered as a feature in another feature package.
73
Feature Language Extension
Domain Statement contains the
definition of the condition variables,
domain variables events
domain BasicTelephony {variables:
DTenum State {DIALING, OUTPULSING, BUSY, AUDIBLE, TALKING, RINGING, DISCONNECT, IDLE};
State state= State.IDLE; // initial valueevents:
TerminationRequest;Busy;Ringing;Answer;Disconnect;Onhook;Offhook;Digits;TimeOut;
}
74
Feature Language Extension
A Feature has the following
Program Unit Condition Part Body Part
anchor feature Pots { domain BasicTelephony; Phone fone; Router rt; public Pots (Phone fone, Router rt) { this.fone = fone; this.rt = rt; } // constructor for anchor feature PotsMakeCall { condition: state.equals(State.IDLE); event: Offhook;
{ fone.applyDialTone(); state = State.DIALING; }}…}
75
Feature Language Extension
Correct program unit is executed depending on the event being sent and the condition part evaluating to be true.
When we have more than one program unit and/or features satisfying the criteria to be executed we need to resolve the precedence
76
Feature Language Extension - example
feature DoNotDisturb {domain BasicTelephony;anchor POTS;Router rt;…
SayBusy {condition: all;event: TerminationRequest e; {
Busy b = new Busy();rt.sendEvent
(Event.FromPhoneID, b);}
}}
77
Feature Language Extension - example
feature package QuietPhone {domain: BasicTelephony;Phone fone;Router rt;features: DoNotDisturb, POTS(fone, rt), CatchAll;priorityPrecedence (DoNotDisturb, POTS, CatchAll);// Constructorpublic QuietPhone (Phone fone, Router rt) {
this.fone = fone ;this.rt = rt ;
}}
79
FLE’s Exception Handling Mechanism
Exceptions in FLE-EHM are special events called exception events
Events are represented as OOP classes. There is a fine line of difference
between the OOP exception objects and FLE exception events. Events are represented as objects.
Therefore all exception events are objects. With some special properties related to
exception handling.
80
FLE – Exceptions
Exceptions are events? Exceptions in reality are events. FLE
takes the exception concept closer to real-life.
Takes advantage of the event driven language , FLE
New exceptions can be derived from the existing ones using inheritance
81
FLE – Exceptions
FLE exceptions have all the advantages of Java exceptions.
They also have the advantages of the FLE events.
OOP Object FLE Event
FLE Exception event
82
FLE – Exceptions
All the exceptions thrown in a feature are listed in the domain statement
This is done for type checking, so that the FLE compiler will make sure that all the exceptions are handled.
83
FLE – Domain statementdomain BasicTelephony { variables:
DTenum State {DIALING, OUTPULSING, BUSY, AUDIBLE, TALKING, RINGING, DISCONNECT, IDLE}; State state= State.IDLE; //initial value
events:TerminationRequest;Busy;Ringing;…Onhook;Offhook;Digits;
exceptions: // The exceptions this featureBindException // may throw are listed here.
ConnectExceptionMalformedURLException…I/OException;Ringing_CircuitFailure;
AreaCode_Exception;}
84
FLE – Exception handlers
The exception handlers are built in as exception program units
exception program units grouped as the exception features These features can be added or
removed in a single go
85
Program Block 1 Exception Handling Block 1
Program Block 2Exception Handling Block
2
Program Block nException Handling Block
n
...…...
A Simple FLE Program Layout
...…...
FLE FeatureFLE Exception
FeatureFLE Program
86
exceptionFeature DoNotDisturbException (FLException e){
domain BasicTelephony;anchor pots;
/* Handler for someException */ catch_areaCodeException { condition: (evnt.fromAreaCode != 312)
OR (NOT poneBook.isKnown(e.fromPhoneId) ) AND state.equals(busy)); event: TerminationRequest evnt;
exception: areaCodeException e; {
/* do exception handling , say print e.getStackTrace() */}
}/* Handler for phoneBookException */ Catch_phoneBookException
{ Context: onHold Exception: phonebookException e
{If(! fone.restoreBakup(e.phoneBook) )
Throw phoneBookPermntDamageException;Else /* EHM successful */
/* retry with the given context */}
}}
87
FLE – Exception handlers The FLE compiler will check the
exceptions that are listed in each feature package with those of the exception features available in the anchor feature.
If no exception feature has appropriate handler for a particular exception then a compiler error is thrown.
This helps programmer to ensure that all the exceptions are handled.
88
FLE – Exception handlers When an exception is thrown,
corresponding exception feature is found and the exception event is delivered.
The exception feature which has a matching program unit for the exception will consume the exception.
The uncaught exceptions are listed in the throws clause of the feature package.
We do this in feature package because feature package serves as an interface to the feature user who would not have any knowledge of the feature code.
89
FLE – Exception handlers If many handlers need to handle an exception,
using other exception program units then one of the following could be done,
1. Method calls like the following can be used to call an exception program unit.
2. Appropriate precedence list can pass the same exception to more than one handler in the specified order
3. The exception can be rethrown but in which case the exception will be sent out the immediate feature package and should be listed in the “throws” list of the feature package
90
FLE – Exception handlers Method 3 in the above list falls in a slightly different –
this can be used to passing the exception to next level.
Though both method 1 and 2 are technically equivalent, method two (precedence) is recommended over the first for the following reasons,
Precedence list gives a clearer picture of the path of navigation for an exception than the method call style in which the “call” statement usually lies buried inside the program code.
It is easier and time saving to change the precedence list than the method call, if later one decides to change the control flow path.
Further discussion about precedence is in the later part of the presentation.
91
Exception handling model supported by FLE The FLE exception mechanism has
provisions for termination, retry resumption as well
Though resumption is possible at this stage we have not included resumption since the disadvantages outweigh the advantages in this model.
92
Exception handling model supported by FLE
Termination The termination model will terminate
the execution at the point of exception event and throws the exception event
The control is then transferred to event dispatcher i.e. the propagation mechanism
The exception is propagated to the matching handler
93
FLE – Termination model
Feature 1
Event Dispatcher – FLE platform
Feature 2
Exception Feature 1
Exception Feature 2
Exception Feature mFeature n Control flow during an
exception in termination
model
94
feature DoNotDisturb (Phone fone, Router r) {domain BasicTelephony;anchor pots;
SayBusy {condition: (evnt.fromAreaCode != 312) ;event: TerminationRequest evnt; {Busy b = new Busy();
If(!r.sendEvent (evnt.FromPhoneID, b)) throw AreaCode_Exception;
}}
OnHold{condition: (NOT poneBook.isKnown(e.fromPhoneId) )
AND state.equals(busy) event: TerminationRequest evnt;{Hold h = new Hold();
msg_id = phoneBook.getHoldMsg(evnt.fromPhoneId);If(msg_id == EXCEPTION)
throw phoneBookExceptionIf(msg_id != INVALID) h.applyMsg(msg_id);
elseh.applyMsg(DEFAULT);
r.sendEvent(evnt.fromPhoneId, h)}
FLE – Termination
model
95
exceptionFeature DoNotDisturbException (FLException e){
domain BasicTelephony;anchor pots;
/* Handler for someException */ catch_areaCodeException { condition: (evnt.fromAreaCode != 312)
OR (NOT poneBook.isKnown(e.fromPhoneId) ) AND state.equals(busy)); event: TerminationRequest evnt;
exception: areaCodeException e; {
/* do exception handling , say print e.getStackTrace() */}
}/* Handler for phoneBookException */ Catch_phoneBookException
{ Context: onHold Exception: phonebookException e
{If(! fone.restoreBakup(e.phoneBook) )
Throw phoneBookPermntDamageException;Else /* EHM successful */
/* retry with the given context */}
}}
FLE – Termination
model
96
FLE – Retry Model When an exception is encountered,
control will be transferred to the handler.
The handler does the work and at the end will resend the event that led to the exception.
This will transfer control to the same program unit where the exception occurred.
97
FLE – Retry Model
Feature 1
Event Dispatcher – FLE platform
Feature 2
Exception Feature 1
Exception Feature 2
Exception Feature mFeature n Control flow during an
exception in retry model
98
exceptionFeature DoNotDisturbException (FLException e){
domain BasicTelephony;anchor pots;
/* Handler for someException */ catch_areaCodeException { condition: (evnt.fromAreaCode != 312)
OR (NOT poneBook.isKnown(e.fromPhoneId) ) AND state.equals(busy)); event: TerminationRequest evnt;
exception: areaCodeException e; {
/* do exception handling , say print e.getStackTrace() */ pots.sendevent(TerminationRequest evnt)
/* this helps retrying the execution */}
}
FLE –Retry model
99
Propagation mechanism in FLE-EHM
Exception is delivered to the appropriate handler by the propagation mechanism.
The propagation mechanism uses the exception type and the context of the raise point to decide the handler to which the exception will be delivered
When there is more than one matching handler the propagation mechanism uses the precedence list
100
Propagation mechanism in FLE-EHM
There are two types of precedence namely priority precedence and straight precedence.
In priority precedence the first matching handler will be executed.
In straight precedence all the matching handlers will be executed in the given order of priority.
101
Propagation mechanism in FLE-EHM
To address other priority requirements, We use a Hybrid or mixed priority
which is formed as a combination of the above two lists
This list will be able to address all the required combinations to list the priority.
102
Propagation mechanism in FLE-EHM
Priority PrecedencepriorityPrecedence(feature1, feature2, feature3); - In this example the exception event will be consumed by the first matching feature.
Straight Precedence straightPrecedence(feature1,feature2, feature3); – Here the exception event will be delivered to all the features and the matching features will process the exception in the order listed.
Mixed PrecedenceStraightprecedence( priorityPecedence(feature1, feature2), feature3,feature4); - In this example the exception event will be delivered to the first matching feature among feature1 and feature2. Then it will also be delivered to feature3 and feature4. But feature3 and/or feature4 will process the exception only if there is a match.
103
Propagation mechanism in FLE-EHM
Though the precedence list is a language semantics it is as important as any other component of a programming language.
104
Advantages of FLE-EHM • Separation of concern
try {Program Block 1}
Catch {Exception Handling Block 1}
try {Program Block 2}
Catch {Exception Handling Block 2}
try {Program Block n}
Catch {Exception Handling Block n}
...…...
A simple Java Program Layout
105
Program Block 1 Exception Handling Block 1
Program Block 2Exception Handling Block
2
Program Block nException Handling Block
n
...…...
A Simple FLE Program Layout
...…...
FLE FeatureFLE Exception
FeatureFLE Program
106
Advantages of FLE-EHM Not only exceptions but exception handlers can be
reused. Java has not included the so called run-time
exceptions in its exception checking mechanism. This is because the founders of Java felt that it will be too much of a trouble for a programmer to handle all the exceptions especially the numerous run-time exceptions (e.g. divide by zero etc.).
In FLE since handlers can be reused, a developer can include default handlers for all the common exceptions during compilation and so FLE can be made to check for all the exceptions without adding burden to the developers.
107
Advantages of FLE-EHM The FLE’s precedence mechanism provides an
elegant way to override the default handlers for specific exceptions.
So the developer can use general handlers to handle all but a few exceptions for which he can have his own handlers.
Development is made easier. Once the exceptions are clearly defined then different developers can work on the program and exception handlers without depending on each other.
It will be much easier to upgrade either the program part or exception handling part as and when required.
108
Advantages of FLE-EHM Middle-ware independent exception
handling Using feature language if one has to implement
a soft-phone application, this can be done using sockets or RMI. Depending on this choice the exception handling code will change too.
But in FLE one can have exception code for both RMI and sockets and can just add the one that they need and compile.
Changing the above will be as simple as removing the existing feature and adding the required one in just a single go. We do not have to search and change code throughout the program.
109
Advantages of FLE-EHM Middle-ware independent exception handling
Soft phone application feature RMI exception feature
Socket exception feature
Feature Package 1Feature Package 2
Soft phone application feature
RMI exception feature
Soft phone application feature
Socket exception feature
Feature available
110
Advantages of FLE-EHM
Exception Reuse The exceptions can be reused unlike
the return value or the signal mechanism.
A standard library of exception can be built and this will save development time of standard exception handling features
111
Advantages of FLE-EHM
Exception handler reuse Exception handlers can also be
reused. This feature is not supported by Java.
Exception handler libraries can be created. Handlers can be included by merely adding them to the exception feature package and compiling them.
112
Advantages of FLE-EHM If we decide to work on exception handling
after completing the actual code we need to make certain compromises in Java. In java, we have to specify all the exceptions in
the throws list and then at the outer most blocks those exceptions should be handled.
After completing the actual code we have to dig into the code to add the exception handlers.
In FLE we can have a catchall handler in the beginning which will handle all the exceptions. Once we are done with the actual code then we can build the handlers and add them to the exception feature. We do not have to modify the actual code at all.
113
Advantages of FLE-EHM The precedence list in the exception feature gives
developers the flexibility to change to handlers or the order of execution by simply changing the precedence list.
Since exceptions are modeled as objects, they carry valuable additional information to the handlers.
Re-throwing exceptions is also made possible in a simple way. The handlers have to throw a new exception or have to re-thrown the actual exception.
Developers have to provide appropriate handlers to handle such exceptions.
114
Code generation / compiler
FLE programs are compiled using the following tools Java Compiler Compiler (JavaCC) Java Tree Builder (JTB)
top related