Handling exceptions at the top level

Another place where you would normally handle exceptions is at the very top level of the program. Why? One reason is that we may want to avoid the program from crashing due to an uncaught exception. The top level of the program is the very last gate to catch anything, and the program has an option to either recover from the failure (such as doing a soft reset) or gracefully close all the resources and shut down.

When a computer program finishes execution, it normally returns an exit status back to the shell where the program was invoked. In Unix, the usual convention is to indicate successful termination with a zero status and unsuccessful termination with a nonzero status.

Consider the following pseudocode:

try
# 1. do some work related to reading writing files
# 2. invoke an HTTP request to a remote web service
# 3. create a status report in PDF and save in a network drive
catch ex
if ex isa FileNotFoundError
println("Having trouble with reading local file")
exit(1)
elseif ex isa HTTPRequestError
println("Unable to communicate with web service")
exit(2)
elseif ex isa NetworkDriveNotReadyError
println("All done, except that the report cannot be saved")
exit(3)
else
println("An unknown error has occurred, please report. Error=", ex)
exit(255)
end
end

We can see from the previous code that, by design, we can exit the program with a specific status code for different error conditions so that the calling program can handle the exception properly.

Next, we will take a look at how to determine where an exception was originally raised from a deeply nested execution frame.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.42.168