The throw Statement
This lesson explains in-depth the working of a throw statement.
We'll cover the following
The throw
statement #
throw
throws an exception object and this terminates the current operation of the program. The expressions and statements that are written after the throw statement are not executed. This behavior is according to the nature of exceptions: they must be thrown when the program cannot continue with its current task.
The exception types Exception
and Error
#
Only the types that are inherited from the Throwable
class can be thrown. Throwable
is almost never used directly in programs. The types that are actually thrown are types that are inherited from Exception
or Error
, which themselves are the types that are inherited from Throwable
. For example, all of the exceptions that “Phobos” throws are inherited from either Exception
or Error
.
Error
represents unrecoverable conditions and is not recommended to be caught. Therefore, most of the exceptions that a program throws are the types that are inherited from Exception
.
Note: Inheritance is a topic related to classes.
Exception
objects are constructed with a string value that represents an error message. You may find it easy to create this message with the format()
function from the std.string
module:
Get hands-on with 1400+ tech skills courses.