exception handling
error identification
programming
software development
debugging

How do I determine what type of exception occurred?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

To determine what type of exception occurred, inspect the exception object's runtime type instead of guessing from the message text. Most languages also let you catch specific exception classes directly, which is usually the cleanest way to distinguish error cases.

Start by Catching the Exception Object

In Python, the exception instance tells you both its type and its message:

python
1try:
2    value = int("abc")
3except Exception as exc:
4    print(type(exc).__name__)
5    print(str(exc))

Output:

text
ValueError
invalid literal for int() with base 10: 'abc'

type(exc).__name__ gives the class name. If you need to test the type programmatically, use isinstance.

python
1try:
2    open("missing.txt")
3except Exception as exc:
4    if isinstance(exc, FileNotFoundError):
5        print("The file does not exist.")

Catch Specific Types When You Can

The best time to determine the type is often during the catch or except step itself.

python
1try:
2    number = 10 / 0
3except ZeroDivisionError:
4    print("Division by zero")
5except ValueError:
6    print("Bad input")

This is better than catching everything and then decoding the message text later, because exception types are part of the language's error model while messages may change or be localized.

The Same Principle in C#

In C#, inspect GetType() or catch the exact exception type directly.

csharp
1try
2{
3    int number = int.Parse("abc");
4}
5catch (Exception ex)
6{
7    Console.WriteLine(ex.GetType().FullName);
8    Console.WriteLine(ex.Message);
9}

Or, better:

csharp
1try
2{
3    int number = int.Parse("abc");
4}
5catch (FormatException)
6{
7    Console.WriteLine("The input is not a valid integer.");
8}
9catch (OverflowException)
10{
11    Console.WriteLine("The number is outside the valid range.");
12}

This is more explicit and makes the program's recovery logic easier to read.

Stack Traces Add Context

Knowing the type is not always enough. The stack trace tells you where the exception happened and how the code reached that point.

In Python:

python
1import traceback
2
3try:
4    {}["missing"]
5except Exception:
6    traceback.print_exc()

In C#, logging frameworks usually record both the type and stack trace when you pass the exception object directly.

That combination is what you want in production logs: type, message, and stack trace together.

Re-Throw Carefully When You Need More Context

Sometimes you detect the exception type, add context, and then let the failure continue upward. In that case, preserve the original exception rather than replacing it blindly.

In Python, raise a new exception from exc when the outer layer needs a clearer domain-specific message. In C#, prefer wrapping with an inner exception or rethrowing with throw; when you want to keep the original stack trace intact.

Avoid Relying on Message Text

A common beginner pattern is:

python
if "file not found" in str(exc):
    ...

That is fragile. Messages can change between library versions, platforms, or languages. Exception types are much more stable and should drive your branching logic whenever possible.

Common Pitfalls

The biggest pitfall is catching a broad base type too early and then handling every failure the same way. That hides useful distinctions between input errors, file errors, permission errors, and programming bugs.

Another mistake is branching on the exception message instead of the exception class. Messages are for humans. Types are for code.

People also forget to log the stack trace. Even when you know the exception type, you still need the location and call path to debug the real cause.

Summary

  • Determine exception type from the exception object itself, not from the message text.
  • Catch specific exception classes whenever possible.
  • Use type(exc) or isinstance in Python and GetType() or typed catch blocks in C#.
  • Log the stack trace alongside the type so you know where the error came from.
  • Use exception types to drive recovery logic and messages only for display or diagnostics.

Course illustration
Course illustration

All Rights Reserved.