If a language has try catch statements, you can think of every function returning a tuple with a hidden variable that indicates whether there was an error, in addition every time a function is called, a hidden statement first checks whether this variable is positive, and then proceeds to return early and return with an error. Since a function both checks the error value of its called methods and returns an error if it exists, the error effectively travels up the call stack until the entry point is reached, in which case execution is halted.
You can then think of a try statement as overriding the typical hidden statement of every function call within the try block. Instead of checking for the error variable and returning early if it's true, execution now exits the try block and continues to the catch block instead. If the end of the try block is reached without an error in any of the functions, the catch block is skipped.
It might seem silly and complicated to use this extra logic path, in fact, some languages like Go choose to make this model explicit and functions look like this:
Code:
error, value = divide(3,0)
if error:
print("division by 0")
Some other languages, like Java, provide tools to limit the added complexity of exceptions by forcing exceptions to be declared as part of the function's return type, while maintaining the implicit control flow:
Code:
int divide(int x, int y) throws Exception{
//...
}
//this compiles
String goodDivision(String command) throws Exception{
int x,y = parse(command);
return String(divide(x,y));
}
// This fails because there is a potentially unhandled exception.
String badDivision(String command){
int x,y = parse(command);
return String(divide(x,y));
}
String okDivision(String command){
int x,y = parse(command);
try{
return String(divide,x,y));
}catch{
return "Error";
}
}
The purpose of exceptions is purely semantic, they convey information about the unhappy path, and they cluster all possible problems that you do not wish to handle. As a programmer you will use classical control flow for most scenarios you can think of, and when these scenarios start becoming rarer and rarer, you just bunch them up as Miscellanea and move on. For example:
Code:
if address in country:
approve()
else address in foreginCountries:
reject()
else address in bastardNations:
nationalize()
else address in moon:
reject
else:
log("I don't understand the address: " + address)
throw Exception
Last edited by _dave_; 09-10-2020 at 03:51 AM.
Reason: [code] tags