Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAlexander Davison
65,469 PointsPython 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) {
System.out.println(err.getMessage());
}
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
~Alex
1 Answer
Chris Howell
Python Web Development Techdegree Graduate 49,702 PointsSo 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
try:
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.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
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
Alexander Davison
65,469 PointsAlexander Davison
65,469 PointsThank you very much! I was planning to use it and now I finally can :)