Is this function correct? - python

Is it correct to call that function in some exceptions ?
Is that process correct ? Is it better to process each exceptions ?
def close_all():
try:
ftp.close()
except:
pass
try:
tar.close()
except:
pass
try:
savelist.close()
except:
pass
try:
os.remove(tarname)
except:
pass
exit()
Thanks in advance.

I think you should handle each exception one by one. This will shorten your code. First of all note all the exceptions that ftp.close() and other methods will raise. Then handle them one by one.
Example:
>>> a = 5 # a is an integer
>>> b = "Bingo" # b is a string
>>>
>>> def add_five():
try:
c + 5 # c is not defined. NameError exception is raised
except NameError:
b + 5 # b is a string. TypeError exception is raised
except TypeError:
a + 5 # a is int. No exception is raised
except:
# This last except clause is just in case you forgot to handle any exception
pass
>>>

Related

Python import list of exceptions from string

My code its something like this:
if Number == 1:
except 1
except 2
If Number2 == 2:
except 1
except 2
How i can import a list of exceptions? without writing it everytime? something like:
ListExcept = ['ExceptError1', 'ExceptError2']
if Number == 1:
except ListExcept
Sorry for my bad example and english
A try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs.
We can use a tuple of values to specify multiple exceptions in an except clause.
You cannot use list!
TEST 1
try:
# do something
a = 10
b = 0
c = a/b
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
del a
del b
try:
# do something
b = 0
a = '10'
c = a/b
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
## No ERRORS
TEST 2
del a
del b
try:
# do something
a = 10
c = a/b
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-23-3726f056c576> in <module>()
30 # do something
31 a = 10
---> 32 c = a/b
33
34 except (TypeError, ZeroDivisionError):
NameError: name 'b' is not defined
TEST 3
FIXING
## fixing above error
try:
# do something
a = 10
c = a/b
except (TypeError, ZeroDivisionError, NameError):
# handle multiple exceptions
# TypeError and ZeroDivisionError and NameError
pass

How can I catch an exception raised inside of a catch clause, If the finally clause corresponding to the catch clause contains a return statement?

Suppose that:
TEF is a try-except-finally block.
an exception is raised from within the try clause of TEF
The finally clause, F of block T contains a return statement
TEF contains an except clause E
an exception e is raised inside of E
How can we catch e from outside of clause F and outside of clause E?
If that was confusing, then some code is shown below:
def e():
out = "hello world"
try:
raise ValueError("my name is Sarah")
except BaseException as exc:
# HOW DO I CATCH THE FIRST OF THE FOLLOWING
# exceptions from outside of this, current,
# except clause?
raise ValueError("secret info it would be good to know")
raise AttributeError
raise type("Hell", (Exception,), dict())()
[0, 1, 2][99999]
class AnythingYouCanThinkOf(Exception):
pass
raise AnythingYouCanThinkOf
out = "definitely not `hello world`"
finally:
return out
print(e())
print("No error!!! wowza!")
The code above prints:
hello world
No error!!! wowza!
If we comment out the line out = "hello world" then we get UnboundLocalError: local variable 'out' referenced before assignment. However, I am still not sure how to recover ValueError("secret info it would be good to know")
Also, if you put almost the same code outside of the function e, you get very different results. Why?
if True:
out = "hello world"
try:
raise ValueError("my name is Bob")
except BaseException as exc:
# HOW DO I CATCH THE FIRST OF THE FOLLOWING
# exceptions from outside of this, current,
# except clause?
raise ValueError("what is this madness?")
class AnythingYouCanThinkOf(Exception):
pass
raise AnythingYouCanThinkOf
out = "definitely not `hello world`"
finally:
print(out)
The above results in unhandled exception ValueError: what is this madness? before, we got No error!!! wowza!

Python try/except depending on variable

i need continue in program after except when variable is True but when variable is False need exit program.
I think there will be if else but I'm not sure how to use it.
for examlpe:
var = True
try:
print 2/0
except:
exit(1)
... continue executing
var = False
try:
print 2/0
except:
exit(1)
... exit
Thanks for comments.
This ought to do the trick, by the way you should probably use raise.
var = True
try:
print 2/0
except:
if not var:
# I recommend using raise, as it would show you the error
exit(1)
If you have a number of except groups which will need to use the var try this
Note that you can expand myexcept using decorators or closures in order to set up additional processing within the exception as well. Since a function is an object, you can use a different specialfunc() for every except: that you write. You can set up the myexcept to handle calls to specialfunc() with arguments as well using the variable arguments process as shown below
def specialfunc1():
# put the special function code here
def specialfunc2(arg1):
# put the processing here
def specialfunc3(arg1, arg2):
# put the processing here
def myexcept(var, e, specialfunc, *args)
print 'Exception caught for ', e
if var:
specialfunc(*args)
else:
raise # This raises the current exception to force an exit
try:
# code you are testing
2/0
except Error1, e:
myexcept(var, e, specialfunc1)
except Error2, e:
myexcept(var, e, specialfunc2(arg1))
except Error3, e:
myexcept(var, e, specialfunc3(arg1, arg2))
except: # this default forces the regular exception handler
# remaining code

What does except really do in Python?

I'm really new in Python and a have no experience with exceptions but I've read all the documentation and couldn't find an answer ... so I'm looking for a deeper view in except's semantics.
When we have for example:
try:
x = 2
except GreaterThanOne:
print("The value is greater than one")
In this case I want the message to be printed.Is there a way for the GreaterThanOne class(exception) to be defined to raise when the entered value is greater than one ?
Ok, let me be more specific ...
Every error raises by a specific rule which should be add in the error attributes, am I right ?
For example:
try:
myvalue = x / y
except ZeroDivisionError:
print("Some error message printed ...")
So when I use this code and enter for y to be 0 the exception ZeroDivisionError will raise ... Can I for example redefine ZeroDivisionError to raise like this but if y is set to be ... 2 or 3 or any other value ?
Input:
x = 10
y = 2
try:
myvalue = x / y
except ZeroDivisionError:
print("division by 2")
Output: division by 2
Here's an example that should help you understand. Run this in your Python interpreter and watch how the exception is raised and caught (or not caught) when you call set_val(2).
# Defining our Exception subclass:
class GreaterThanOne(Exception):
pass
# The global value we pretend to care about:
val = 0
# Function to set a value but possibly raise our new Exception
def set_val(new_val):
if new_val > 1:
raise GreaterThanOne("%d > 1" % new_val)
val = new_val
# Catching exception:
try:
set_val(0)
set_val(1)
set_val(2)
except GreaterThanOne:
print "Whoops - one of those values was greater than one"
# Not catching exception:
set_val(0)
set_val(1)
set_val(2)
set_val(3)
an try-except block catches exception in this block.
try:
#some stuff here
except ExceptionClass as e:
#Exception handling here
the class after the except keyword indicates which kind of exception you want to catch. Usually you give a specific class, like ValueError or KeyError. You can also use the Exception class, to catch any exception. Because all the other exceptionclasses inhert from Exception.
so if you want to use this construct, an exception needs to be raised, Either by a function / method you call, or you raise it yourself with the raise keyword.
like this:
try:
raise KeyError('Just for test')
except KeyError as e:
#Exception handling here
The try except doesn't automagically inspect the whole code between it, it just looks for exceptions... Or to be more specific, it looks for those exceptions you tell it to look for.
Of course you can also inspect the exception instance.
try:
raise KeyError('Just for test')
except KeyError as e:
print e.args
For more information, please see:
http://docs.python.org/2/tutorial/errors.html

How to write multiple try statements in one block in python?

I want to do:
try:
do()
except:
do2()
except:
do3()
except:
do4()
If do() fails, execute do2(), if do2() fails too, exceute do3() and so on.
best Regards
If you really don't care about the exceptions, you could loop over cases until you succeed:
for fn in (do, do2, do3, do4):
try:
fn()
break
except:
continue
This at least avoids having to indent once for every case. If the different functions need different arguments you can use functools.partial to 'prime' them before the loop.
I'd write a quick wrapper function first() for this.
usage: value = first([f1, f2, f3, ..., fn], default='All failed')
#!/usr/bin/env
def first(flist, default=None):
""" Try each function in `flist` until one does not throw an exception, and
return the return value of that function. If all functions throw exceptions,
return `default`
Args:
flist - list of functions to try
default - value to return if all functions fail
Returns:
return value of first function that does not throw exception, or
`default` if all throw exceptions.
TODO: Also accept a list of (f, (exceptions)) tuples, where f is the
function as above and (exceptions) is a tuple of exceptions that f should
expect. This allows you to still re-raise unexpected exceptions.
"""
for f in flist:
try:
return f()
except:
continue
else:
return default
# Testing.
def f():
raise TypeError
def g():
raise IndexError
def h():
return 1
# We skip two exception-throwing functions and return value of the last.
assert first([f, g, h]) == 1
assert first([f, g, f], default='monty') == 'monty'
It seems like a really odd thing to want to do, but I would probably loop over the functions and break out when there were no exception raised:
for func in [do, do2, do3]:
try:
func()
except Exception:
pass
else:
break
Here is the simplest way I found, just embed the try under the previous except.
try:
do()
except:
try:
do2()
except:
do3()
You should specify the type of the exception you are trying to catch each time.
try:
do()
except TypeError: #for example first one - TypeError
do_2()
except KeyError: #for example second one - KeyError
do_3()
and so on.
if you want multiple try statments you can do it like this, including the except statement. Extract (refactor) your statements. And use the magic of and and or to decide when to short-circuit.
def a():
try: # a code
except: pass # or raise
else: return True
def b():
try: # b code
except: pass # or raise
else: return True
def c():
try: # c code
except: pass # or raise
else: return True
def d():
try: # d code
except: pass # or raise
else: return True
def main():
try:
a() and b() or c() or d()
except:
pass
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

Categories

Resources