The try-catch Statement to Catch Exceptions

This lesson explains how we can use try-catch statements to catch exceptions.

The try-catch statement to catch exceptions #

As we’ve seen earlier in this chapter, a thrown exception causes the program execution to exit all functions, and this finally terminates the whole program.
The exception object can be caught by a try-catch statement at any point on its path as it exits the functions. The try-catch statement models the phrase “try to do something, and catch exceptions that may be thrown.” Here is the syntax of try-catch:

try {
    // the code block that is being executed, where an exception may be thrown
} catch (an_exception_type) {
    // expressions to execute if an exception of this type is caught
} catch (another_exception_type) {
    // expressions to execute if an exception of this other type is caught

// ... more catch blocks as appropriate ...
} finally {
    // expressions to execute regardless of whether an exception is thrown
}

Let’s start with the following program, which does not use a try-catch statement at this stage. The program reads the value of a die from a file and writes its value to the standard output:

Get hands-on with 1200+ tech skills courses.