Lecture

Exception Handling with try/except

Sometimes programs crash because of unexpected errors, such as dividing by zero or accessing a file that does not exist.

Instead of crashing, you can use exception handling to deal with errors gracefully.

Python provides four key tools:

  • try
  • except
  • else
  • finally

1. try and except

Wrap risky code in a try block. If an error happens, Python jumps to the except block.

try: result = 10 / 0 except ZeroDivisionError: print("Oops! You can't divide by zero.")
  • The division causes an error.
  • Python skips the crash and shows a message instead.

2. Handling Multiple Error Types

You can catch different types of exceptions in separate except blocks.

Handling Multiple Error Types
try: num = int("abc") except ValueError: print("That's not a valid number.") except TypeError: print("Type mismatch.")
  • This handles a ValueError caused by int("abc").

3. else and finally

  • else runs only if no error occurs.
  • finally runs no matter what, even if there is an error.
else and finally
try: value = int("42") except ValueError: print("Conversion failed.") else: print("Conversion succeeded:", value) finally: print("Done checking.")
  • else confirms success.
  • finally is good for cleanup, such as closing files or connections.

Summary

KeywordPurpose
tryRun risky code
exceptHandle specific errors
elseRuns if no exception occurred
finallyAlways runs, used for cleanup
Quiz
0 / 1

In Python, the 'finally' block in a try/except structure is only executed if an exception is thrown and caught.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result