During program execution an error can be thrown.
Instead of ending the program an error can be caught
and a certain
code can be executed.
Syntax for handling error:
Let's look at the following example:
Output:
Since an error is thrown in the try block, the code from the catch block is called.
An error can be thrown when a validation fails in setter.
Example:
Output:
At line 38
a negative number (-1
)
is passed for age of the person object. This causes
an error to be throw (due to line 21
).