Menu
Coddy logo textTech

What Is Exception Handling?

Exception handling is a way for a program to respond to errors that occur while it runs. Code that might fail goes in a protected block, such as try, and when an error is raised, control jumps to a handler, such as except or catch, instead of crashing.

By Kevin Spektor, Co-founder & CTO

Updated September 24, 2026

A program that asks people for their age will sooner or later receive "twenty" instead of 20. Converting that text is a runtime error: int("twenty") raises ValueError, and with no plan for it the program stops. Exception handling is that plan. You mark the code that might fail and write the code that runs if it does.

Next year you will be 35
Not a number: twenty
Next year you will be 20
Done

The bad answer is reported, and the loop carries on with the next one. Without the try, the program would have printed one line and then a traceback.

How exception handling works

  1. The code inside try runs normally.
  2. An operation fails, and the runtime raises an exception: an object with a type (ValueError) and a message (invalid literal for int() with base 10: 'twenty').
  3. The try block stops at that line. Its remaining lines are skipped, which is why "Next year you will be" is not printed for "twenty".
  4. The runtime compares the exception's type with each except clause, from top to bottom, and runs the first one that matches.
  5. After the handler finishes, the program continues with the first line after the whole try statement.
  6. If no clause matches, the exception leaves the current function and the search continues in the function that called it, then in that function's caller. This is called unwinding the call stack. If the search reaches the top of the program without a match, the program ends with a traceback.

Step 6 means the handler does not have to be in the function where the error happens. Here the failure is two calls deep, and the handler at the bottom still catches it:

parsing 4.50
parsing free
Could not add the prices: could not convert string to float: 'free'

float("free") failed inside parse_price. Neither parse_price nor total had a handler, so both were abandoned, and "3.20" was never parsed. This is the main design choice exception handling gives you: handle an error where you know what to do about it, which is often far from where it happened.

try, except, else and finally

Python's try statement has two more optional parts. else runs only when the try block finished without an exception. finally runs in every case: after success, after a handled exception, and even when the function returns from inside the try.

no error
finally runs either way
2.0
b was zero
finally runs either way
None

finally is where cleanup goes: closing a file, releasing a lock, closing a database connection. In Python the with statement does this cleanup for files automatically, and it is the usual choice for them.

Raising your own exceptions

Exceptions are not only for errors the language detects. When your own function receives input it cannot work with, it can raise an exception to refuse, and the caller decides what happens next. Defining a small exception class gives the error a name that describes it.

70
Refused: cannot take 250, balance is 100

Python uses raise. Java, C++ and JavaScript use throw for the same thing.

Exception handling in other languages

LanguageKeywordsWorth knowing
Pythontry, except, else, finally, raiseEvery exception is an object that inherits from BaseException
Javatry, catch, finally, throw, throwsChecked exceptions such as IOException must be caught or declared with throws
C++try, catch, throwNo finally; destructors clean up as the stack unwinds
JavaScripttry, catch, finally, throwErrors in async code are caught with try around await
CnoneFunctions return an error code, and many set errno
Gonone for ordinary errorsFunctions return an error value that the caller checks

The same parsing example in Java looks like this:

try {
    int age = Integer.parseInt("twenty");
    System.out.println(age + 1);
} catch (NumberFormatException e) {
    System.out.println("Not a number: " + e.getMessage());
} finally {
    System.out.println("done");
}

Java splits exceptions into two groups. Checked exceptions, such as IOException, describe problems outside the program's control, and the compiler refuses to build code that neither catches nor declares them. Unchecked exceptions, subclasses of RuntimeException such as NullPointerException, usually mean a bug, and the compiler does not force you to handle them.

Common mistakes

  • Catching everything. A bare except: in Python also catches KeyboardInterrupt, so Ctrl+C stops working, and except Exception: catches bugs you never planned for. Catch the specific type you know how to handle.
  • Swallowing the error. except ValueError: pass hides the problem. At minimum, print or log what went wrong.
  • A try block that is too big. Wrap only the lines that can raise the exception you are catching, so an unrelated error is not handled by mistake.
  • Catching bugs instead of fixing them. An IndexError from a loop that runs one step too far is a mistake in the code. Handling it keeps the wrong code alive.
  • Expecting catch to stop a crash in C or C++. A segmentation fault is a signal from the operating system, not an exception, and on Linux and macOS a C++ catch (...) never sees it.

Where to go next

The errors that exception handling responds to are described on the runtime error page, and the crash it cannot catch on the segmentation fault page. For the full syntax, read the guides to Python exceptions, Java try and catch, C++ exceptions and JavaScript try and catch. The Java course and the Python course both practice them with real exercises.

Frequently Asked Questions

What are the 5 keywords in Java exception handling?
try, catch, finally, throw and throws. try marks the code to watch, catch handles a specific exception type, and finally runs cleanup code whether or not an exception occurred. throw raises an exception, and throws in a method signature declares which checked exceptions the method can pass on to its caller.
What is exception handling in C++?
C++ uses try, catch and throw. Any type can be thrown, but by convention you throw an object derived from std::exception, such as std::runtime_error, and catch it by reference: catch (const std::exception& e). C++ has no finally; cleanup happens in destructors, which run automatically as the stack unwinds.
What is the difference between an error and an exception?
In everyday use, an error is anything that goes wrong and an exception is the object a language uses to report it. Java draws a sharper line: Exception covers problems a program can reasonably handle, while Error, such as OutOfMemoryError or StackOverflowError, signals a failure of the JVM that a program usually should not try to catch. In Python, ValueError and ZeroDivisionError are both exceptions despite their names.
What is the difference between throw and throws in Java?
throw is a statement that raises one exception at that point: throw new IllegalArgumentException("negative age");. throws is part of a method declaration that lists the checked exceptions the method may pass to its caller: void load() throws IOException. The compiler then makes every caller either catch that exception or declare it too.
Does exception handling make code slower?
Entering a try block is cheap in most modern languages. Since Python 3.11, a try costs almost nothing when no exception is raised, and the major C++ compilers add no run-time cost to the path where nothing is thrown. Raising and catching an exception is much slower than an if test, so in performance-critical loops, check for common cases instead of relying on exceptions.
Coddy programming languages illustration

Learn to code with Coddy

GET STARTED