Trying to figure out the except statement in Python - python

I am having some trouble understanding ways to use the "except" statement in Python. I am a horrendous coder right now, so my apologies in advance.
Here is the small code I am trying to run:
def mathWorks():
print " Answer the following: 5 + x = 10"
x = int(raw_input("Please type your answer: "))
if x == 5:
print "You are correct!"
else:
print "You are incorrect!"
break
except ValueError:
print "That is not an integer!"
mathWorks()
I think what I am trying to accomplish is pretty self explanatory. Unfortunately I am getting an "invalid syntax" for the "except" statement in this code.
What all am I doing wrong here?

except has to come after a try block. This signals the section of code that should have the exception handled:
try:
x = int(raw_input("Please type your answer: "))
except ValueError:
print "That is not an integer!"
Read it as 'try this, then do this if it fails'. Note it's good practice to do as little as possible in the try block - this ensures you don't catch errors you don't mean to (as does specifying the type of exception to catch, which you were already doing).
In this case, you might want to call sys.exit(1) in the except block as well, otherwise the program will continue (and fail with another error).

It's used like this:
try: # try code here
except: # except errors here

For your code, there is a "else" statement, you should use "else" statement after all of your except statements.
This is not directly related to your question, but you may encounter this further down.
Please refer to the original document for more details:
https://docs.python.org/2/tutorial/errors.html

Related

Not catching specific errors with Try and Except

Alright, so I've got a try and except block watching out for exceptions.
This is all normal but when you've got a loop you can't stop the code usually, as there's no specific bit saying "Don't catch KeyboardInterrupt errors" or something alike
Is there anything that let's try and except blocks exclude specific errors? (or an alternative)
My code
while 1:
if ques == 'n':
try:
newweight = int(input('Please enter a number'))
exit()
except:
print('Please enter a valid number')
Now this will create an infinite loop as the "exit()" will not happen as it will get raised an as exception, and it will thus create an infinite loop. Is there any way for this to not happen?
To prevent a user entering a non-integer value, you want to catch a TypeError so you can change except: to except ValueError: and it will then catch any invalid inputs. That should cover you sufficiently.

Does a try except stop right away in python if an exception is found?

If I have a try except block in my python code, and the first line of my try statement raises an exception will it automatically move on to exception or will it finish the try block first?
try:
int(string)
string = "This was a mistake, can't int string"
except:
pass
Here is it checking if it can int(string), which it can't, and then it immediately moves onto except, or does it do the string assignment first?
When I run it, it seems like it stops right away, but I want to know if that's happening for sure or something else.
Thanks
Let's try it.
try:
1/0
print("what?")
except:
print("nope")
Output:
nope
>>>
When an exception is raised it moves on to the except.
From the python docs, I found this,
"The try statement works as follows.
First, the try clause (the statement(s) between the try and except keywords) is executed.
If no exception occurs, the except clause is skipped and execution of the try statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above."
Cheers!
Hope it helps!
#the try block is to run the process
try:
string = "This was a mistake, can't int string"
#you are parsing the string into an int
int(string)
#this block is to capture the exception when it is raised
except:
#here I am just printing the exception
print('Exception')
#the pass is to pass the execution and follow the remaining process.
pass
Output:
Exception
>>>
Well, that the whole point of an error handler. When an error occurs in out program, it crashes, it won't simply skip the error line.
try:
int(string)
string = "This was a mistake, can't int string"
except:
pass
So if the try block finishes even after an error occurred in the middle, then the error handler'd seem a bit pointless.
There seem to be some issue with your program and maybe your understanding of the try except block.
First of all, from the block of code you have provided, it seems to me like string isn't even defined yet when you try to pass int(string).
Secondly, the string variable which you seem to be defining under seems to me like is something you are trying to print to the console once the program spits out an error and passes to the except block. If this is what you are trying to do, then your code should look something like this:
try:
int(string)
except:
print("This was a mistake, can't int string")
If you were to run the code provided above, you would indeed confirm that the try except statement is working as it would print "This was a mistake, can't int string" into the console instead of giving an error. Hope this was somewhat helpful and understandable. You got this chief, keep grinding!

Where should I print my output at this simple exception handling?(Python)

Hello guys is there any differences between print my output in "try" clause or putting it after "except" clause with "else:"?
here is the code:
try:
Value1 = int(input("Type the first number: "))
Value2 = int(input("Type the second number: "))
Output = Value1 / Value2
except ZeroDivisionError:
print("Attempted to divide by zero!")
else:
print(Output)
or this?
try:
Value1 = int(input("Type the first number: "))
Value2 = int(input("Type the second number: "))
Output = Value1 / Value2
print(Output)
except ZeroDivisionError:
print("Attempted to divide by zero!")
I mean which one is better? because the result is same.
Thanks.
Like you already know we are talking about error handling when we are using try...except.
When an error is generated by an operation (or other statements) Python will stop the try block execution and is passed down to the first except block that matches the raised exception.
In case there isn't an except clause that matches our exception, it is passed on the outer try statement. This until it's handled or no handler is found, the raised exception becomes an unhandled exception and execution stops with a message of the error traceback.
In addition to except block we can use a finally block, that will be executed regardless of whether an exception occurs, and else block. The last one is useful for code that must be executed if the try clause does not raise an exception.
Your examples
How you said this two pieces of code gives the same result. However, with we read on documentation page of Python we have this affirmation:
"The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement."
Simple speaking if you have different statements that raises the same error, but for one them you aren't interested in catching it, move it to else clause. Look on this question on stack to understand better.
So in your case you can let print statement in try block because you will not catch some particular exceptions from it and there isn't much difference in this case where you put the print statement. However, I think the second example is a good logic separation of type "If no errors where founded then let's execute print".
The else clause is run only when no exception is thrown.
So the reason why you'd want to put it in there is to make it explicit: you only want to print the output if there was no exception.
As you mentioned, in your code, there's no functional difference to what happens.
See the docs for more information.
The first one will work fine as per your expectations (assuming that you don't want to bring up the python error prompt and halt the program).
It simply prescribes that IF 2nd digit is zero then it won't print the Python error prompt and pass it to the print command (And that's how it should be). Otherwise, in every other case, no matter whatever the divisor is, it will always give an output, so that way you eliminate nearly all loopholes.
Suggestion:
Keep the input type as float instead of int, that way you'll be able to print the division for decimal numbers input also. Ex-2/3

What are exceptions in Python?

I've read three beginner-level Python books, however, I still don't understand exceptions.
Could someone give me a high level explanation?
I guess I understand that exceptions are errors in code or process that cause the code to stop working.
In the old days, when people wrote in assembly language or C, every time you called a function that might fail, you had to check whether it succeeded. So you'd have code like this:
def countlines(path):
f = open(path, 'r')
if not f:
print("Couldn't open", path)
return None
total = 0
for line in f:
value, success = int(line)
if not success:
print(line, "is not an integer")
f.close()
return None
total += value
f.close()
return total
The idea behind exceptions is that you don't worry about those exceptional cases, you just write this:
def countlines(path):
total = 0
with open(path, 'r') as f:
for line in f:
total += int(line)
return total
If Python can't open the file, or turn the line into an integer, it will raise an exception, which will automatically close the file, exit your function, and quit your whole program, printing out useful debugging information.
In some cases, you want to handle an exception instead of letting it quit your program. For example, maybe you want to print the error message and then ask the user for a different filename:
while True:
path = input("Give me a path")
try:
print(countlines(path))
break
except Exception as e:
print("That one didn't work:", e)
Once you know the basic idea that exceptions are trying to accomplish, the tutorial has a lot of useful information.
If you want more background, Wikipedia can help (although the article isn't very useful until you understand the basic idea).
If you still don't understand, ask a more specific question.
The best place to start with that is Python's list of built-in exceptions, since most you'll see derive from that.
Keep in mind that anybody can throw any error they want over anything, and then catch it and dismiss it as well. Here's one quick snippet that uses exceptions for handling instead of if/else where __get_site_file() throws an exception if the file isn't found in any of a list of paths. Despite that particular exception, the code will still work. However, the code would throw an uncaught error that stops execution if the file exists but the permissions don't allow reading.
def __setup_site_conf(self):
# Look for a site.conf in the site folder
try:
path = self.__get_site_file('site.conf')
self.__site_conf = open(path).read()
except EnvironmentError:
self.__site_conf = self.__get_site_conf_from_template()
Python's documentation: http://docs.python.org/2/tutorial/errors.html
For a high-level explanation, say we want to divide varA / varB. We know that varB can't equal 0, but we might not want to perform the check every time we do the division:
if varB != 0:
varA / varB
We can use exceptions to try the block without performing the conditional first, and then handle the behavior of the program based on whether or not something went wrong in the try block. In the following code, if varB == 0, then 'oops' is printed to the console:
try:
varA / varB
except ZeroDivisionError:
print 'oops'
Here is a list of exceptions that can be used: http://docs.python.org/2/library/exceptions.html#exceptions.BaseException
However, if you know how it may fail, you can just open a python console and see what exception is raised:
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
Exceptions are unexpected events that occur during the execution of a program. An exception might result from a logical error or an unanticipated situation.
In Python, exceptions (also known as errors) are objects that are raised (or thrown) by code that encounters an unexpected circumstance.
The Python interpreter can also raise an exception should it encounter an unexpected condition, like running out of memory. A raised error may be caught by a surrounding context that “handles” the exception in an appropriate fashion.
If uncaught, an exception causes the interpreter to stop executing the program and to report an appropriate message to the console.
def sqrt(x):
if not isinstance(x, (int, float)):
raise TypeError( x must be numeric )
elif x < 0:
raise ValueError( x cannot be negative )
Exceptions are not necessarily errors. They are things that get raised when the code encounters something it doesn't (immediately) know how to deal with. This may be entirely acceptable, depending on how you make your code. For instance, let's say you ask a user to put in a number. You then try to take that text (string) and convert it to a number (int). If the user put in, let's say, "cat", however, this will raise an exception. You could have your code handle that exception, however, and rather than break, just give the user a small message asking him to try again, and please use a number. Look at this link to see what I'm talking about: http://www.tutorialspoint.com/python/python_exceptions.htm
Also, you usually handle exceptions with a try, except (or catch) block. Example:
try:
integer = int(raw_input("Please enter an integer: "))
except Exception, exc:
print "An error has occured."
print str(exc)
Hope it helps!

running code if try statements were successful in python

I was wondering if in python there was a simple way to run code if a try statement was successful that wasn't in the try statement itself. Is that what the else or finally commands do (I didn't understand their documentation)? I know I could use code like this:
successful = False
try:
#code that might fail
successful = True
except:
#error handling if code failed
if successful:
#code to run if try was successful that isn't part of try
but I was wondering if there was a shorter way.
You want else:
for i in [0, 1]:
try:
print '10 / %i: ' % i, 10 / i
except:
print 'Uh-Oh'
else:
print 'Yay!'
You are looking for the else keyword:
try:
#code that might fail
except SomeException:
#error handling if code failed
else:
# do this if no exception occured
Your try block should be the code you want to execute, and your except should be killing the program. I'd need to understand your object better to give a better answer.
In OO programming, you want to "Tell, don't ask" so keep all the logic that should happen in the try block, and then your error handling in the except block.

Categories

Resources