Python Exception Handling: Getting the error message

How do you get the message of a error message (inside the except block)?

I know you can do it in Java like this:

try {
    // Let's assume this code causes a IllegalArgumentException error.
} catch(IllegalArgumentException err) {

However, I can't seem to find out how to do it in Python. I also searched the Python Documentation, didn't find anything helpful.

I'd appreciate help :)

Tagging Kenneth Love


1 Answer

Chris Howell
Chris Howell
Python Web Development Techdegree Graduate 49,488 Points

Hey Alexander Davison

So from the Python Docs: Handling Exceptions

You will want to scroll down a few examples (the yellow bits)

You will see the usage of Try/Except example such as this.

import sys

    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
    print("Unexpected error:", sys.exc_info()[0])

Where the relevant part of the answer to your question lies in this part:

except OSError as err:

Any error raised from OSError will be stored in err

Thank you very much! I was planning to use it and now I finally can :)