Try-Except

Basic Try-Except

  1. # catch any exception
  2. try:
  3. result = 10 / 0
  4. except:
  5. print("Error occurred")

Specific Exception

  1. # catch specific exception
  2. try:
  3. result = 10 / 0
  4. except ZeroDivisionError:
  5. print("Cannot divide by zero")

Exception Object

  1. # access exception details
  2. try:
  3. result = 10 / 0
  4. except ZeroDivisionError as e:
  5. print(f"Error: {e}")

Multiple Except Blocks

  1. # handle different exceptions
  2. try:
  3. value = int(input())
  4. result = 10 / value
  5. except ValueError:
  6. print("Invalid number")
  7. except ZeroDivisionError:
  8. print("Cannot divide by zero")

Catch Multiple Exceptions

  1. # one handler for multiple
  2. try:
  3. # code
  4. pass
  5. except (ValueError, TypeError):
  6. print("Type or value error")

Try-Except-Else

  1. # else runs if no exception
  2. try:
  3. result = 10 / 2
  4. except ZeroDivisionError:
  5. print("Error")
  6. else:
  7. print("Success")

Try-Except-Finally

  1. # finally always runs
  2. try:
  3. file = open("data.txt")
  4. except FileNotFoundError:
  5. print("File not found")
  6. finally:
  7. print("Cleanup")

Exercises - Part 1

  1. # catch all exceptions?
  2. try:
  3. x = 1 / 0
  4. except:
  5. pass
  6. #ans: catches everything (not recommended)

Exercises - Part 2

  1. # what is e?
  2. try:
  3. x = 1 / 0
  4. except ZeroDivisionError as e:
  5. type(e)
  6. #ans: ZeroDivisionError instance

Exercises - Part 3

  1. # else when?
  2. try:
  3. x = 5
  4. except:
  5. print("Error")
  6. else:
  7. print("OK")
  8. #ans: "OK" (no exception)

Exercises - Part 4

  1. # finally with return?
  2. def func():
  3. try:
  4. return 1
  5. finally:
  6. print("Finally")
  7. func()
  8. #ans: prints "Finally", returns 1

Exercises - Part 5

  1. # nested try?
  2. try:
  3. try:
  4. x = 1 / 0
  5. except ValueError:
  6. pass
  7. except ZeroDivisionError:
  8. print("Caught")
  9. #ans: "Caught"

Exercises - Part 6

  1. # multiple except order?
  2. try:
  3. x = 1 / 0
  4. except Exception:
  5. print("General")
  6. except ZeroDivisionError:
  7. print("Specific")
  8. #ans: "General" (first match wins)

Exercises - Part 7

  1. # finally without except?
  2. try:
  3. x = 5
  4. finally:
  5. print("Done")
  6. #ans: valid, prints "Done"

Exercises - Part 8

  1. # else without except?
  2. try:
  3. x = 5
  4. else:
  5. print("OK")
  6. #ans: SyntaxError (needs except)

Exercises - Part 9

  1. # exception in finally?
  2. try:
  3. x = 5
  4. finally:
  5. y = 1 / 0
  6. #ans: raises ZeroDivisionError

Exercises - Part 10

  1. # bare except position?
  2. try:
  3. x = 1 / 0
  4. except ValueError:
  5. pass
  6. except:
  7. print("Other")
  8. #ans: "Other"

Google tag (gtag.js)