Am I able to check for multiple error types with one try and except statement?

Question

In Python, am I able to check for multiple error types with one try and except statement?

Answer

Yes, it is possible to check multiple error types with a single try and except statement.

For the except, we can include multiple error types listed within a tuple. It will check if any of the listed errors are encountered.

You can also do a general except without a specified error type, but that is not recommended as it will catch any errors, including ones we don’t want to check.

Example

# Multiple error types listed.
try:
  line of code
except(TypeError, NameError, ...):
  ...  

# Not recommended
try:
  line of code
except:
  ...
16 Likes

How to handle any unexpected error which occurred while running the code?

There should not be any. Of course, during development, errors will always occur, but that is what debugging is for. Once you submit your code to whoever requested it, you should be confident that it will run without error for any input within the agreed-upon preconditions.

3 Likes

if an error occurs, you can fix the error in the code and handle the way you want it.

@patrickd314, there are very few people who can write bug free code, after deployment there is usual ongoing development to fix bugs and add new features.

3 Likes

@stetim94: Quite so.

Hi, guys and girls. Help me understand this, please.
Let me see if I understood if I use an except without a specified error type the code will catch every kind of error, right?

I just didn’t understand why would we want only some kind of error. Python already doesn’t do it automatically?

One special case may be that we only wish to catch a certain type of error, which we then handle, otherwise we let Python raise the exception. This is because we want to understand the underlying condition that raised the error (a likely problem in our code) and then address that issue in the code so the error never comes up again.

7 Likes

Sometimes we may elect to tailor a remedy to the specific type of error that occurred. For example, if we are validating user input, we can provide an appropriate message when a problematic value is entered. See the following example:

# Slice the pizza!
pizza_mass = 320.0 # 320.0 grams
while True:
  try:
    num_slices = int(input("Serve the pizza as how many slices? "))
    slice_mass = pizza_mass / num_slices
  except ValueError: # Input cannot be interpreted as an int.
    print("Enter an integer, please.")
    continue
  except ZeroDivisionError: # Input was 0.
    print("Cannot serve it as zero slices.")
    continue
  if num_slices < 0: # Input was negative.
    print("Cannot serve a negative number of slices.")
    continue
  break

print("The mass of each pizza slice is {:0.2f} grams.".format(slice_mass))
31 Likes

Is function except looks like a function that ignores standard error that we defined with condition statement?

except, when given an error type will only trap errors of that type. All others will be handled by the interpreter as raised exceptions. Does this make sense to you?

1 Like

so in what purpose we use the except function actually? Does std error good for debugging codes?

The aim of except is to permit us to define a default action for error types we can identify as probable in our code. The other types should not be subverted, but allowed to raise exceptions if they occur.

We may not have considered the full range of errors possible in our code so must rely on the interpreter to catch them for us. If we are not fully aware of the types of errors our code might raise, then all the more reason to not short circuit error handling but leave it for the interpreter so we can learn from the experience. Exceptions are our chief debugging tool, but must not become a crutch. Learn the causes behind errors and write code to insulate from them.

Bottom line, study and learn all the possible exceptions and their causes so we can recognize code that might raise one. Without this knowledge, we should not use except in our code, but rather let the program terminate on raised exceptions. Use the traceback information to seek out all possible causes, and note the type. It’s a learning process. except is not meant as a workaround.

15 Likes

Thanks for the explanation. Really help.:star_struck:

1 Like

I can’t seem to grasp this concept. What I under is… ‘except’ is used to catch input errors the user may encounter and acts accordingly based on their input??

Lots of things can happen that will raise an exception in the runtime session. We depend upon this to alert us of issues in our code. It’s not something we would ever simply turn off, but try...except allows us to at least catch the identifiable error types, that is, those we know might occur with varying user inputs, etc.

Let’s examine a Scrabble dictionary, for example…

# scrabble letter scores dictionary
letters = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ "]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 
3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10, 0]
lookup = dict(zip(letters, points))

We know what will happen with a wrong input, but let’s just look at it to see the error type that gets raised…

>>> lookup['a']
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    lookup['a']
KeyError: 'a'
>>> 

This error was caused only because the case didn’t match, so we fix that and run it again.

letters = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ "]
letters += [x.lower() for x in letters]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 
3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10, 0]
lookup = dict(zip(letters, points * 2))
>>> lookup['a']
1
>>> lookup['q']
10
>>> lookup['z']
10
>>> lookup[' ']
0
>>> lookup['&']
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    lookup['&']
KeyError: '&'
>>> 

That gets rid of the case difference issue, and it doesn’t add that greatly to the data load. Sure we can address it in the code, but why go to the bother if we’ve done it here? We still have the errant input issue to deal with, as witnessed above.

def get_letter_score(letter):
    return lookup[letter]

This gives us something to build upon and improve that will be re-usable.

>>> get_letter_score('&')
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    get_letter_score('&')
  File ".../scrabble_letter_scores_dictionary.py", line 12, in get_letter_score
    return lookup[letter]
KeyError: '&'
>>> 

Note that it was the polling of the lookup object that raised the error (we can see that identified in the error message). This is where we insert our try..except

def get_letter_score(letter):
    try:
        return lookup[letter]
    except:
        pass

Notice that I’ve only added except to prevent an EOF error while parsing. It is expected with try. We’ve not added any handling yet so won’t see an exception raised. Nothing will happen.

>>> get_letter_score('z')
10
>>> get_letter_score('&')
>>> 

Now we can select the error type to isolate. All the rest will be trapped by the interpreter.

def get_letter_score(letter):
    try:
        return lookup[letter]
    except KeyError:
        return print ("Wrong alphabet!")
>>> get_letter_score('&')
Wrong alphabet!
>>> 
>>> get_letter_score(a)
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    get_letter_score(a)
NameError: name 'a' is not defined
>>> 

See how other exception is not interfered with?

4 Likes

Really good! Thank you mtf. :slight_smile:

1 Like

So it is more useful to use except for error types we already understand.

Purpose is the determining factor. There is no one correct or explicit way. We are the determiners. It is up to us which path we choose. Sorry to be so general. Every situation creates its own dimensions. There is no one right way,

Exceptions are there to not only warn us, but to stop the process since from that point on it would be feeding garbage into the program. We want to be aware of those outcomes so we can design around them. With the right design those outcomes are not possible.

When user input comes into play we have to double the guards. It’s usually str type if it has come from a standard input. Our program needs a layer of insulation that confirms the data is fit to pass to the other side. String data is one thing, but numeric data is quite another.

Our program needs to confirm that the string data can be recast as a number type, whether int or float doesn’t matter. There are no coercive measures in Python that I’m aware of so the built-ins are the way to go. That is a vector on which we can plan for an exception Do we trap it, or do we test for it? This is the real question.

1 Like

Thank you. This is insightful.

1 Like

What is the raise statement used in the exercise?