Skip to content

Joseph-T-Gordon

A complete log of all recent projects and skills

Menu
  • About me
  • Posts/Projects
  • Resume/Certifications
Menu

Post #51 (Python Programming) – Multiple exceptions and the default exception

Posted on June 22, 2023June 26, 2023 by admin

In one of my previous posts I brought up the idea of using try and except within python to handle errors but what if you want different responses for different errors? Well you’re in luck, you can have multiple exceptions for different errors and even have a default exception. This default exception must always be the last one listed and it will be executed if you receive an error and the other exceptions don’t specify it, each specific can only have one exception in the associated try and except

Ex:

try:

var = int(input(“Please input a positive integer and I’ll return the reciprocal: “))

result = 1 / var

print(var)

except ZeroDivisionError:

print(“Please enter a value other than zero”)

except ValueError:

print(“We are looking for a number”)

except:

print(“Are you trying to make things difficult”)

Result:

Please input a positive integer and I’ll return the reciprocal: 0

Please enter a value other than zero

Please input a positive integer and I’ll return the reciprocal: No

We are looking for a number

As you can see that is the power of exceptions, they can be very useful if you want to avoid your code spitting out confusing errors to your user and instead offer a more friendly explanation.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

© 2025 Joseph-T-Gordon | Powered by Minimalist Blog WordPress Theme