← Back to Python Course | Chapter 10: Exception Handling | Lesson 2 of 5

Python try-except

try-except is like a safety net: you try something risky, and if it fails you catch the problem and do something sensible. That way the program does not crash.
Syntax
python
try:
    # risky code
except ExceptionType as error:
    # handle error
except (TypeA, TypeB):
    # handle either

The try-except Block

The code inside a try block runs first, and if any statement in it raises an exception, execution jumps immediately to the matching except block instead of continuing -- if no exception occurs, the except block is simply skipped entirely.

Example: The try-except Block

python
try:
    print(10 / 2)  # no exception raised here
except ZeroDivisionError:
    print("This does not run")

Handling Multiple Exceptions

Writing several except clauses lets you handle different error types differently (a missing file vs. bad data need different fixes), or you can group related exception types into a single except (ValueError, TypeError): block when they should be handled the same way.

Example: Handling Multiple Exceptions

python
try:
    int("abc")
except (ValueError, TypeError):  # handles either exception type the same way
    print("Caught ValueError or TypeError")

Catching Exception as Variable

'except ValueError as e:' saves the exception object to a variable so you can inspect its actual message with str(e), which is far more useful for logging or debugging than just knowing 'a ValueError happened somewhere'.

Example: Catching Exception as Variable

python
try:
    int("abc")
except ValueError as e:  # saves the exception object for inspection
    print(str(e))

Nested try-except Blocks

Placing a try/except inside another try/except lets you attempt a fallback recovery action and still catch failures in that recovery itself -- useful for something like 'try the primary server, and if reaching it fails, try a backup server, and handle failure of that too'.

Example: Nested try-except Blocks

python
try:
    try:
        raise ConnectionError("primary server down")
    except ConnectionError:
        raise ConnectionError("backup server also down")  # failure of the fallback itself
except ConnectionError as e:
    print(e)

Avoiding Bare except

A bare 'except:' with no exception type catches literally everything, including things like KeyboardInterrupt that a user might trigger intentionally to stop the program -- catching 'except Exception:' instead still catches ordinary errors but lets those system-level signals through.

Example: Avoiding Bare except

python
try:
    int("abc")
except Exception as e:  # catches ordinary errors but lets KeyboardInterrupt through
    print("Caught ordinary errors, not KeyboardInterrupt:", e)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using a bare except: that also catches KeyboardInterrupt, so Ctrl+C no longer stops the program; catch specific exceptions.
  2. Silencing errors with except Exception: pass, which hides real bugs.
  3. Putting too much code inside try, so you cannot tell which line caused the caught error.
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.