What is an exception?


#1

Question

This exercise mentions an exception, what is that?

Answer

If something is an error, it should not be handled by your program in a way that allows the user to continue using the program, as it can cause unexpected behavior and issues. They should be fixed!

An exception, on the other hand, is something that you might want to allow your program to handle. Later you’ll come across something called catching exceptions, and that’s what this means. Exceptions typically don’t cause your program to behave in unexpected ways if they occur, so long as you handle them properly.


FAQ: Learn Python - Python Syntax - Handling Errors
#2

Hi, i still cant not fully understand the concept of exceptions. can i get a more simpler explanation? thanks


#3

For example:

get_user_input = raw_input("enter an integer: ")
trying_convert = int(get_user_input)

we ask the user for a integer by prompting for input with raw_input. But raw_input stores the result as string, so we need to convert to integer.

If the users enters 5, converting to integer goes fine. But if the enters hello, python will raise an error, given this can’t be converted to integer

The error raised by python will exit the program

If we then want to give the user another chance of entering input, we will first need to make an exception for the error so our program can continue running


#4

another change, or another chance?


#5

So in other words, an exception is just something to allow someone to still run the program after an error? I.e. incorrect password try again? I understand it may not be exactly like that, but that was the closest analogy I could think of.


#6

errors produces by python, like a ValueError (like in my earlier example) or a NameError.

lets say you have this code:

print x

you will get a NameError (x isn’t defined). This we could prevent by making exception:

try:
   print x
   # except keyword which allows us to create an exception
   # then the exception we expect, in this case a NameError
except NameError:
  print "x is not defined"

no, that would be more something like:

# not secure, don't use this anywhere important
# it just serves as an example

# give the user 3 attempts to enter there password
for i in range(3):
    password = raw_input("enter your password: ")
    # check length of password
    if len(password) > 7:
        print "valid password"
        break
else:
    # 3 incorrect passwords where entered. 
   # because i use for/else, the else clause only runs
   # when loop condition becomes false
   # not when the loop breaks
   print "invalid password"

So password validation is not a python exception, a password validation is just code we write, and then print a message to user.