for example, our old friend
bracketRoot(double a, double b), if f(a) and f(b) are
the same sign, we are not guaranteed a root and trouble will follow.
For example, in the case of bracketRoot, check signs before call.
If you are implementing both the caller and callee, one can check for consistancy in the caller and assume all is well in the callee.
If you are implementing a library or class to be used by others, you probably have to check all inputs for error in your library methods.
public ErrorCode bracketRoot(double a, double b, double e, double[] val);and return our answer in val[0]; (In some language (like C on UNIX), this is really the only choice, and many C libraries are specified this way). and many
The basic problems Exception mechanisms are trying to solve are:
public class BracketException extends IOException{
public BracketException(){}; // empty constructor
public BracketException(String msg){ super(msg)} //allows error msg
}
throw which takes an instance of an exception
type. For example, in bracketRoot we might have:
// init fa, fb
if((fa > 0) && (fb > 0)) || (fa < 0) && (fb < 0)){ // same sign, error!
throw new BracketException(); // must use new to get instance
...
// code to do stuff
}
throws in the method definition.
public bracketRoot(double a, double b, double e) throws BracketException{
// init fa, fb
if((fa > 0) && (fb > 0)) || (fa < 0) && (fb < 0)){ // same sign, error!
throw new BracketException(); // must use new to get instance
...
// code to do stuff
}
throws the error.
try,catch>/code> pair.
- Any code that might throw an exception we want to handle is
wrapped in a
try block. This is followed by one or more
catch blocks (one for each Exception type we
want to handle) which contains code that handle the error.
try{
// Code that can throw an exception
bracketRoot(a,b,e);
}
catch(BracketException e){
..Code to handle exception e...
}
..Execution resumes here...
- The code in the catch block is ONLY executed when the exception is
thrown.
- In either case, execution continues immediate after the
last catch block (unless the catch block does a throw).
- Finally blocks are useful for factoring out code that should be executed
no matter what: normal execution, caught exception, exception to be passed to
higher level (re-thrown).
try{
..Code that can throw an exception..
}
catch(Exception e){
..Code to handle exception e...
}
finally{
..Code here always executes. Good place to clean up...
}
..Normal execution resumes here...
- Warning: Throw/try/catch mechanism is high overhead. Use sparingly.
A little error checking at high level goes a long way.