Get a quick-start on using try/catch to handle errors and exceptions.
Consider the below example that expects name to be provided to the program. If name is provided you will go ahead and store record.
|
|
The big problem with the above code is absence of any kind of feedback to the caller (or user).
You can do this to manage that error and notify the caller.
|
|
Execution halts at the if
statement if there is an error.
Use a try/catch if you want to handle this much more gracefully.
|
|
You could also use try/catch to suppress error, do something, and continue execution.
|
|
As you get deeper, you may also want to locally handle exceptions from certain parts of the code.
|
|
These are referred to as ‘nested try/catch’ blocks.
When you there is an error in inner block control transfers to inner catch
. There after the inner catch can further throw error and transfer control to outer catch
. Or, manage the error and let outer try
block at peace.
If there is no inner catch
block, the exception will go all the way to the outer catch
(or to the caller if there is no catch
at all).
Finally, use a finally
block to execute statements both in case there is no error, or an error was caught.
|
|