
























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

























Exceptions
How to Take Advantage ofthe Exception Mechanism
Error handling
-^
Exceptions
Learning Objectives UnderstandingExceptions
-^
If division by zero is attempted the calculator just keeps trying tosubtract and never stops. Very exciting!
-^
Okay for a machine with an operator but what about an automaticmachine?
-^
Need to take action upon encountering certain error conditionslike "division by zero"
-^
Architecture modified to detect error conditions and branch tohandler code.
-^
So how do we handle the situation?
Programmers never think they will make errors
-^
Programmers are wrong a lot!
-^
Want to make code robust
-^
Want to force users to maintain robustness
-^
Need a "clean" way of handling problems
Could have methods return a value that tells uswhether or not we had an error?^ –
Then can’t return anything else or – Have to return a composite object
-^
Even with some kind of error code^ –
Does it give us enough information? – Does it give us flexibility – Does it include a way to make sure we check it?
How would we use?….
Another way to deal with error handling is to have the value of a global variable
represent the error.
int iErrorValue = 0; public void someMethod( ) {
// do someMethod’s stuff here // if there is an error, then set iErrorValue = 1 } public void someOtherMethod( )
{
// do someOtherMethod’s stuff here // if there is an error, then set iErrorValue = 2 } public void someThirdMethod( )
{
// do someThirdMethod’s stuff here^ // if there is an error,
then set iErrorValue = 3
}
continued
-^
But
: What if the run-time error stopped us from continuing?
-^
For example
: What if
someMethod( )
failed in such a way that we cannot goon to
someOtherMethod( )
?
-^
To cope, we find ourselves with codethat’s nearly as messy as the earlierexample which featured multiple nested-ifs:
public
void
doIt()
{
someMethod(); someOtherMethod(); someLastMethod(); if
(iErrorValue
==
...
if
(iErrorValue
==
...
if
(iErrorValue
==
...
}
Exceptions
-^
Sense: "I take exception to that."
-^
Exceptions are thrown^ –
like an NFL referee throws a penalty flag
-^
Exceptions can be thrown by Matlab
-^
Exceptions can be thrown by you!
What happens when an exception is thrown
-^
What are your choices for handling exceptions
-^
Why and when you should use exceptions
-^
Some typical scenarios
An exception is created
(on the heap)
The current "context" is halted/aborted
-^
Execution starts in some error handling code^ –
Can be in current method – Can be external to current method
Handle in current method^ try
% Code that might throw an exception catch
% Code that handles exception
Handle outside current method (make the calling method deal with it!)