This is my homework assignment:
And this is what I have so far. Sorry if I'm way off. I'm new to Python:
def safe_input():
try:
return safe_input()
except KeyboardInterrupt:
return None
But when I test it out, instead of returning nothing, it returns KeyboardInterrupt.
How can I fix this?
I think you meant to return input()
def safe_input():
try:
return input() # here
except KeyboardInterrupt:
return None
I got this piece of code that is catching an error. Is it possible to write the error handling inside a function for example and then just reference to it inside the code? The goal would be to have all the error handling in a separate file and just call the class inside the code when needed.
This is the normal way and its working fine
#!/usr/bin/env python3
def main():
try:
x = int("foo")
except ValueError:
print("I cought a ValueError")
if __name__ == '__main__': main()
I would like to try something like this, but is something like this possible? and how is it done in a proper way?:
#!/usr/bin/env python3
#All the error handeling goes here:
def exceptValueError():
except ValueError:
print("I cought a ValueError")
def exceptZeroDivisionError():
except ZeroDivisionError:
print("You cant devide by zero")
#Code goes here
def main():
try:
x = int("foo")
exeptValueError()
if __name__ == '__main__': main()
This gives me:
except ValueError:
^
SyntaxError: invalid syntax
Is it possible to use try and instead of except use a function that contains an except? I assume that is not really possible.
def exeptValueError():
except ValueError:
print("I cought a ValueError")
This won't work because there is no try block before the except block (the try block in main doesn't count).
You could do the following, which would still be close to what you want
def exceptValueError():
print("I caught a ValueError")
def main():
try:
x = int("foo")
except ValueError:
exceptValueError()
Hi im currently doing a program like this.
class MyError(Exception):
def __init__(self, text = "Correct")
self.text = text
def __str__(self):
return (self.kod)
class Atom(self):
.
.
.
try:
function()
else:
raise MyError("Incorrect use of function")
def main():
try:
a = Atom()
except:
# Here i want to print the error that was raised
What I think I understand is that the error is raised in an object created in Atom().
But I want to send it to my main program and do the print of the error MyError there.
Is it possible to do this and how should I write it so that the correct text of exception is printed since i will have several different error messages.
If i come to the except statement I would want to get the message "Incorrect use of function" printed.
It seems that you're pretty close:
class MyError(Exception):
def __init__(self, text = "Correct")
self.text = text
def __str__(self):
return (self.kod)
class Atom(self):
.
.
.
try:
function()
except: # try: ... else: raise ... seems a bit funky to me.
raise MyError("Incorrect use of function")
def main():
try:
a = Atom()
except Exception as err: # Possibly `except MyError as err` to be more specific
print err
The trick is that when you catch the error, you want to bind the exception instance to a name using the as clause. Then you can print it, look at it's attributes, re-raise or pretty much do anything you choose with it.
Please note that this code still isn't "clean". Generally, you want to limit exception handling as much as possible -- only catch exceptions that expect to see and that you know how to handle. Otherwise, you can sometimes mask hard to find bugs in your code. Because of this:
try:
do_something()
except:
...
is discouraged (it catches all sorts of things like KeyboardInterrupt and SystemExit) ... Instead:
try:
do_something()
except ExceptionIKnowHowToHandle:
...
is advised.
Firstly, never do a blank except. That will catch all errors, including things like KeyboardInterrupt - so you won't be able to ctrl-c out of your program. Here you should just catch MyError.
The except clause also allows you to assign the actual exception to a variable, which you can then print or do anything else with. So you can do:
try:
...
except MyError as e:
print e.text
I have to deal with a large quantity of try/except. I'm in doubt about the right way of doing it.
Option 1:
inst = Some(param1, param2)
try:
is_valid = retry_func(partial(inst.some_other), max_retry=1)
except RetryException, e:
SendMail.is_valid_problem(e)
if is_valid:
print "continue to write your code"
...
*** more code with try/except ***
...
Option 2:
inst = Some(param1, param2)
try:
is_valid = retry_func(partial(inst.some_other), max_retry=1)
if is_valid:
print "continue to write your code"
...
*** more code with try/except ***
...
except RetryException, e:
SendMail.is_valid_problem(e)
In the Option 1, even is the exception is raised, "is_valid" will be tested and I don't need that.
In the Option 2, is what I think is correct but the code will look like a "callback hell".
What option should I choose or what option is the correct one?
Keep your exception handling as close as possible to the code that raises the exception. You don't want to accidentally mask a different problem in code you thought would not raise the same exception.
There is a third option here, use the else: suite of the try statement:
inst = Some(param1, param2)
try:
is_valid = retry_func(partial(inst.some_other), max_retry=1)
except RetryException, e:
SendMail.is_valid_problem(e)
else:
if is_valid:
print "continue to write your code"
...
*** more code with try/except ***
...
The else: suite is only executed if there was no exception raised in the try suite.
From your conditions, condition 1 is better and you can use else instead of if is_valid
Here are some of Try Except:
Here is simple syntax of try....except...else blocks:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
The except clause with multiple exceptions:
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
The try-finally clause:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
I think option 1 is better. The reason is that you should always put inside a try except only the code which you expect to throw the exception. Putting more code increase the risk of catching an unwanted exception.
Make sure that if an Error will occur, keep the cause inside the try statement. That way, it will catch the error and sort it out in the except section. There is also finally. If the try doesn't work, but the "except" error doesn't work, it will act out the "finally" statement. If there is no finally, the program will get stuck. This is a sample code with try and except:
import sys
import math
while True:
x=sys.stdin.readline()
x=float(x)
try:
x=math.sqrt(x)
y=int(x)
if x!=y:
print("Your number is not a square number.")
elif x==y:
print("Your number is a square number.")
except(ValueError):
print("Your number is negative.")
ValueError is the error you get from sqrt-ing a negative number.
Sometimes I need the following pattern within a for loop. At times more than once in the same loop:
try:
# attempt to do something that may diversely fail
except Exception as e:
logging.error(e)
continue
Now I don't see a nice way to wrap this in a function as it can not return continue:
def attempt(x):
try:
raise random.choice((ValueError, IndexError, TypeError))
except Exception as e:
logging.error(e)
# continue # syntax error: continue not properly in loop
# return continue # invalid syntax
return None # this sort of works
If I return None than I could:
a = attempt('to do something that may diversely fail')
if not a:
continue
But I don't feel that does it the justice. I want to tell the for loop to continue (or fake it) from within attempt function.
Python already has a very nice construct for doing just this and it doesn't use continue:
for i in range(10):
try:
r = 1.0 / (i % 2)
except Exception, e:
print(e)
else:
print(r)
I wouldn't nest any more than this, though, or your code will soon get very ugly.
In your case I would probably do something more like this as it is far easier to unit test the individual functions and flat is better than nested:
#!/usr/bin/env python
def something_that_may_raise(i):
return 1.0 / (i % 2)
def handle(e):
print("Exception: " + str(e))
def do_something_with(result):
print("No exception: " + str(result))
def wrap_process(i):
try:
result = something_that_may_raise(i)
except ZeroDivisionError, e:
handle(e)
except OverflowError, e:
handle(e) # Realistically, this will be a different handler...
else:
do_something_with(result)
for i in range(10):
wrap_process(i)
Remember to always catch specific exceptions. If you were not expecting a specific exception to be thrown, it is probably not safe to continue with your processing loop.
Edit following comments:
If you really don't want to handle the exceptions, which I still think is a bad idea, then catch all exceptions (except:) and instead of handle(e), just pass. At this point wrap_process() will end, skipping the else:-block where the real work is done, and you'll go to the next iteration of your for-loop.
Bear in mind, Errors should never pass silently.
The whole idea of exceptions is that they work across multiple levels of indirection, i.e., if you have an error (or any other exceptional state) deep inside your call hierarchy, you can still catch it on a higher level and handle it properly.
In your case, say you have a function attempt() which calls the functions attempt2() and attempt3() down the call hierarchy, and attempt3() may encounter an exceptional state which should cause the main loop to terminate:
class JustContinueException(Exception):
pass
for i in range(0,99):
try:
var = attempt() # calls attempt2() and attempt3() in turn
except JustContinueException:
continue # we don't need to log anything here
except Exception, e:
log(e)
continue
foo(bar)
def attempt3():
try:
# do something
except Exception, e:
# do something with e, if needed
raise # reraise exception, so we catch it downstream
You can even throw a dummy exception yourself, that would just cause the loop to terminate, and wouldn't even be logged.
def attempt3():
raise JustContinueException()
Apart from the context I just want to answer the question in a brief fashion. No, a function cannot continue a loop it may be called in. That is because it has no information about this context. Also, it would raise a whole new class of questions like what shall happen if that function is called without a surrounding loop to handle that continue?
BUT a function can signal by various means that it wants the caller to continue any loop it currently performs. One means of course is the return value. Return False or None to signal this for example. Another way of signaling this is to raise a special Exception:
class ContinuePlease(Exception): pass
def f():
raise ContinuePlease()
for i in range(10):
try:
f()
except ContinuePlease:
continue
Maybe you want to do continuations? You could go and look at how Eric Lippert explains them (if you are ready to have your mind blown, but in Python it could look a bit like this:
def attempt(operation, continuation):
try:
operation()
except:
log('operation failed!')
continuation()
Inside your loop you could do:
attempt(attempt_something, lambda: foo(bar)) # attempt_something is a function
You could use this:
for l in loop:
attempt() and foo(bar)
but you should make sure attempt() returns True or False.
Really, though, Johnsyweb's answer is probably better.
Think that you are mapping foo on all items where attempt worked. So attempt is a filter and it's easy to write this as a generator:
def attempted( items ):
for item in items:
try:
yield attempt( item )
except Exception, e:
log(e)
print [foo(bar) for bar in attempted( items )]
I wouldn't normally post a second answer, but this is an alternative approach if you really don't like my first answer.
Remember that a function can return a tuple.
#!/usr/bin/env python
def something_that_mail_fail(i):
failed = False
result = None
try:
result = 1.0 / (i % 4)
except:
failed = True # But we don't care
return failed, result
for i in range(20):
failed, result = something_that_mail_fail(i)
if failed:
continue
for rah in ['rah'] * 3:
print(rah)
print(result)
I maintain that try ... except ... else is the way to go, and you shouldn't silently ignore errors though. Caveat emptor and all that.
Try the for loop outside the try, except block
This answer had Python 3.4 in mind however there are better ways in newer versions. Here is my suggestion
import sys
if '3.4' in sys.version:
from termcolor import colored
def list_attributes(module_name):
'''Import the module before calling this func on it.s '''
for index, method in enumerate(dir(module_name)):
try:
method = str(method)
module = 'email'
expression = module + '.' + method
print('*' * len(expression), '\n')
print( str(index).upper() + '. ',colored( expression.upper(), 'red'),
' ', eval( expression ).dir() , '...' , '\n'2 )
print('' * len(expression), '\n')
print( eval( expression + '.doc' ), '\n'*4,
'END OF DESCRIPTION FOR: ' + expression.upper(), '\n'*4)
except (AttributeError, NameError):
continue
else:
pass
finally:
pass
Edit: Removed all that stupidity I said...
The final answer was to rewrite the whole thing, so that I don't need to code like that.