Handling multiple exceptions in functions [closed]
up vote
0
down vote
favorite
I have a tiny web-server written in Python 3 using http.server which calls the function translate()
in method do_GET()
like this:
class httpd(BaseHTTPRequestHandler):
def do_GET(self):
self.wfile.write(bytes(f'translate(var[0])', 'utf-8'))
Now in this translate()
function I have several conditional statements and try
and except
blocks roughly like this:
def translate(param):
try:
# do something
except SomeError as some_err:
print("Error: " % some_err)
return ""
if True:
try:
# do something
except SomeOtherError as some_other_err:
print("Error: " % some_other_err)
return ""
except SomeThirdError as some_third_err:
print("Third error: " % some_third_err)
return ""
else:
# additional try and except blocks which print an error and
# return an empty string
The code above is simplified, but in principle I return an empty string if an exception happens and thus my web server returns nothing to client if an exception happens.
Is there a more manageable way to handle this? Specifically, I'm looking to:
- Avoid catching each error via a separate
except
section, while still supporting an error message dependent on error type. - Avoid writing multiple
try
/except
statements, often nested, within my function.
Note: This is a copy of this now deleted question. The solution from that post is included below, but other answers are welcome.
python python-3.x exception error-handling exception-handling
closed as too broad by Martijn Pieters♦ Nov 17 at 17:30
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.
add a comment |
up vote
0
down vote
favorite
I have a tiny web-server written in Python 3 using http.server which calls the function translate()
in method do_GET()
like this:
class httpd(BaseHTTPRequestHandler):
def do_GET(self):
self.wfile.write(bytes(f'translate(var[0])', 'utf-8'))
Now in this translate()
function I have several conditional statements and try
and except
blocks roughly like this:
def translate(param):
try:
# do something
except SomeError as some_err:
print("Error: " % some_err)
return ""
if True:
try:
# do something
except SomeOtherError as some_other_err:
print("Error: " % some_other_err)
return ""
except SomeThirdError as some_third_err:
print("Third error: " % some_third_err)
return ""
else:
# additional try and except blocks which print an error and
# return an empty string
The code above is simplified, but in principle I return an empty string if an exception happens and thus my web server returns nothing to client if an exception happens.
Is there a more manageable way to handle this? Specifically, I'm looking to:
- Avoid catching each error via a separate
except
section, while still supporting an error message dependent on error type. - Avoid writing multiple
try
/except
statements, often nested, within my function.
Note: This is a copy of this now deleted question. The solution from that post is included below, but other answers are welcome.
python python-3.x exception error-handling exception-handling
closed as too broad by Martijn Pieters♦ Nov 17 at 17:30
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.
This is a very broad question. Exception handling is very specific to the use cases involved, and it could well be that your actual application could avoid a bunch of exceptions altogether if restructured. But with the overly genericSomething..Error
exceptions here withdo something
code there is only very broad advice we can give. Context managers could help, but are not a general fits-all solution. Catching a base exception is another. Usingexcept (Exc1, Exc2, Exc3)
then dispatching from there in the exception handler is a 3rd. These all have different characterstics.
– Martijn Pieters♦
Nov 17 at 17:30
But writing all that down is going to require something approaching publishable book status, so I've closed this as Too Broad.
– Martijn Pieters♦
Nov 17 at 17:30
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
I have a tiny web-server written in Python 3 using http.server which calls the function translate()
in method do_GET()
like this:
class httpd(BaseHTTPRequestHandler):
def do_GET(self):
self.wfile.write(bytes(f'translate(var[0])', 'utf-8'))
Now in this translate()
function I have several conditional statements and try
and except
blocks roughly like this:
def translate(param):
try:
# do something
except SomeError as some_err:
print("Error: " % some_err)
return ""
if True:
try:
# do something
except SomeOtherError as some_other_err:
print("Error: " % some_other_err)
return ""
except SomeThirdError as some_third_err:
print("Third error: " % some_third_err)
return ""
else:
# additional try and except blocks which print an error and
# return an empty string
The code above is simplified, but in principle I return an empty string if an exception happens and thus my web server returns nothing to client if an exception happens.
Is there a more manageable way to handle this? Specifically, I'm looking to:
- Avoid catching each error via a separate
except
section, while still supporting an error message dependent on error type. - Avoid writing multiple
try
/except
statements, often nested, within my function.
Note: This is a copy of this now deleted question. The solution from that post is included below, but other answers are welcome.
python python-3.x exception error-handling exception-handling
I have a tiny web-server written in Python 3 using http.server which calls the function translate()
in method do_GET()
like this:
class httpd(BaseHTTPRequestHandler):
def do_GET(self):
self.wfile.write(bytes(f'translate(var[0])', 'utf-8'))
Now in this translate()
function I have several conditional statements and try
and except
blocks roughly like this:
def translate(param):
try:
# do something
except SomeError as some_err:
print("Error: " % some_err)
return ""
if True:
try:
# do something
except SomeOtherError as some_other_err:
print("Error: " % some_other_err)
return ""
except SomeThirdError as some_third_err:
print("Third error: " % some_third_err)
return ""
else:
# additional try and except blocks which print an error and
# return an empty string
The code above is simplified, but in principle I return an empty string if an exception happens and thus my web server returns nothing to client if an exception happens.
Is there a more manageable way to handle this? Specifically, I'm looking to:
- Avoid catching each error via a separate
except
section, while still supporting an error message dependent on error type. - Avoid writing multiple
try
/except
statements, often nested, within my function.
Note: This is a copy of this now deleted question. The solution from that post is included below, but other answers are welcome.
python python-3.x exception error-handling exception-handling
python python-3.x exception error-handling exception-handling
asked Nov 11 at 16:02
jpp
87.3k194999
87.3k194999
closed as too broad by Martijn Pieters♦ Nov 17 at 17:30
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.
closed as too broad by Martijn Pieters♦ Nov 17 at 17:30
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.
This is a very broad question. Exception handling is very specific to the use cases involved, and it could well be that your actual application could avoid a bunch of exceptions altogether if restructured. But with the overly genericSomething..Error
exceptions here withdo something
code there is only very broad advice we can give. Context managers could help, but are not a general fits-all solution. Catching a base exception is another. Usingexcept (Exc1, Exc2, Exc3)
then dispatching from there in the exception handler is a 3rd. These all have different characterstics.
– Martijn Pieters♦
Nov 17 at 17:30
But writing all that down is going to require something approaching publishable book status, so I've closed this as Too Broad.
– Martijn Pieters♦
Nov 17 at 17:30
add a comment |
This is a very broad question. Exception handling is very specific to the use cases involved, and it could well be that your actual application could avoid a bunch of exceptions altogether if restructured. But with the overly genericSomething..Error
exceptions here withdo something
code there is only very broad advice we can give. Context managers could help, but are not a general fits-all solution. Catching a base exception is another. Usingexcept (Exc1, Exc2, Exc3)
then dispatching from there in the exception handler is a 3rd. These all have different characterstics.
– Martijn Pieters♦
Nov 17 at 17:30
But writing all that down is going to require something approaching publishable book status, so I've closed this as Too Broad.
– Martijn Pieters♦
Nov 17 at 17:30
This is a very broad question. Exception handling is very specific to the use cases involved, and it could well be that your actual application could avoid a bunch of exceptions altogether if restructured. But with the overly generic
Something..Error
exceptions here with do something
code there is only very broad advice we can give. Context managers could help, but are not a general fits-all solution. Catching a base exception is another. Using except (Exc1, Exc2, Exc3)
then dispatching from there in the exception handler is a 3rd. These all have different characterstics.– Martijn Pieters♦
Nov 17 at 17:30
This is a very broad question. Exception handling is very specific to the use cases involved, and it could well be that your actual application could avoid a bunch of exceptions altogether if restructured. But with the overly generic
Something..Error
exceptions here with do something
code there is only very broad advice we can give. Context managers could help, but are not a general fits-all solution. Catching a base exception is another. Using except (Exc1, Exc2, Exc3)
then dispatching from there in the exception handler is a 3rd. These all have different characterstics.– Martijn Pieters♦
Nov 17 at 17:30
But writing all that down is going to require something approaching publishable book status, so I've closed this as Too Broad.
– Martijn Pieters♦
Nov 17 at 17:30
But writing all that down is going to require something approaching publishable book status, so I've closed this as Too Broad.
– Martijn Pieters♦
Nov 17 at 17:30
add a comment |
3 Answers
3
active
oldest
votes
up vote
3
down vote
I'm not sure if having nested try
blocks is absolutely necessary in your logic, but I'd try a single try
block with a custom Exception
class. Something like this:
class MyException(Exception):
"""Generic error message."""
def __str__(self):
return self.__doc__
class SomeError(MyException):
"""SomeError message."""
pass
class SomeOtherError(MyException):
"""SomeOtherError message."""
pass
class SomeThirdError(MyException):
"""SomeThirdError message."""
pass
def translate(param):
try:
# do something
...
if cond1:
raise SomeError()
...
if cond2:
raise SomeOtherError()
...
if cond3:
raise SomeThirdError()
...
except MyException as err:
print(err)
return ""
2
@jpp If you raise any subclassed exception you will output the proper message given that you havereturn self.__doc__
in the__str__
method of base class, that's the way sub-classes and inheritance works. I've update the example just to be clear.
– Cartucho
Nov 14 at 14:24
add a comment |
up vote
1
down vote
accepted
How about contextmanager
? To alleviate your concern about custom error messages, you can feed a dictionary mapping error classes to messages of your choice.
Since different operations require different errors to be handled, you can use multiple with
statements, feeding different errors as arguments each time.
Here's a contrived example:
from contextlib import contextmanager
@contextmanager
def error_handling(msg, *exceptions):
try:
yield
except exceptions as my_error:
print(msg[my_error.__class__], my_error)
return ''
def do_stuff(d, key, index):
custom_msg = IndexError: 'You have an Index Error!',
KeyError: 'You have a Key Error!'
with error_handling(custom_msg, IndexError, KeyError):
return d[key][index]
# example prints "You have an Index Error! list index out of range"; then returns ''
do_stuff('a': [0, 1, 2], 'a', 10)
add a comment |
up vote
1
down vote
How about to define a function that has a dictionary contained the whole errors and responses. in this case you can catch an exception one time and send it to a handler
UPDATE :
def handle (e) :
exp = 'IOError' : 'NO such a file in dir ...! ' ,
'KeyboardInterrupt' : 'Exiting ... (Keyboard interruption)',
'IndexError' : ' a sequence subscript is out of range' ,
'NameError' : 'a local or global name is not found'
for key , value in exp.items() :
if e == key :
print (value) #or do whatever you want
def test() :
try :
f = open('no-file' , 'r')
except Exception as e :
handle (type(e).__name__)
if __name__ == "__main__" :
test()
Probably goes without saying, but the...
bit is relevant here, it would be helpful if you can fill them in with a trivial example users can run.
– jpp
Nov 14 at 14:16
you're right, I hope this helps.
– Ali Kargar
Nov 14 at 18:41
add a comment |
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
3
down vote
I'm not sure if having nested try
blocks is absolutely necessary in your logic, but I'd try a single try
block with a custom Exception
class. Something like this:
class MyException(Exception):
"""Generic error message."""
def __str__(self):
return self.__doc__
class SomeError(MyException):
"""SomeError message."""
pass
class SomeOtherError(MyException):
"""SomeOtherError message."""
pass
class SomeThirdError(MyException):
"""SomeThirdError message."""
pass
def translate(param):
try:
# do something
...
if cond1:
raise SomeError()
...
if cond2:
raise SomeOtherError()
...
if cond3:
raise SomeThirdError()
...
except MyException as err:
print(err)
return ""
2
@jpp If you raise any subclassed exception you will output the proper message given that you havereturn self.__doc__
in the__str__
method of base class, that's the way sub-classes and inheritance works. I've update the example just to be clear.
– Cartucho
Nov 14 at 14:24
add a comment |
up vote
3
down vote
I'm not sure if having nested try
blocks is absolutely necessary in your logic, but I'd try a single try
block with a custom Exception
class. Something like this:
class MyException(Exception):
"""Generic error message."""
def __str__(self):
return self.__doc__
class SomeError(MyException):
"""SomeError message."""
pass
class SomeOtherError(MyException):
"""SomeOtherError message."""
pass
class SomeThirdError(MyException):
"""SomeThirdError message."""
pass
def translate(param):
try:
# do something
...
if cond1:
raise SomeError()
...
if cond2:
raise SomeOtherError()
...
if cond3:
raise SomeThirdError()
...
except MyException as err:
print(err)
return ""
2
@jpp If you raise any subclassed exception you will output the proper message given that you havereturn self.__doc__
in the__str__
method of base class, that's the way sub-classes and inheritance works. I've update the example just to be clear.
– Cartucho
Nov 14 at 14:24
add a comment |
up vote
3
down vote
up vote
3
down vote
I'm not sure if having nested try
blocks is absolutely necessary in your logic, but I'd try a single try
block with a custom Exception
class. Something like this:
class MyException(Exception):
"""Generic error message."""
def __str__(self):
return self.__doc__
class SomeError(MyException):
"""SomeError message."""
pass
class SomeOtherError(MyException):
"""SomeOtherError message."""
pass
class SomeThirdError(MyException):
"""SomeThirdError message."""
pass
def translate(param):
try:
# do something
...
if cond1:
raise SomeError()
...
if cond2:
raise SomeOtherError()
...
if cond3:
raise SomeThirdError()
...
except MyException as err:
print(err)
return ""
I'm not sure if having nested try
blocks is absolutely necessary in your logic, but I'd try a single try
block with a custom Exception
class. Something like this:
class MyException(Exception):
"""Generic error message."""
def __str__(self):
return self.__doc__
class SomeError(MyException):
"""SomeError message."""
pass
class SomeOtherError(MyException):
"""SomeOtherError message."""
pass
class SomeThirdError(MyException):
"""SomeThirdError message."""
pass
def translate(param):
try:
# do something
...
if cond1:
raise SomeError()
...
if cond2:
raise SomeOtherError()
...
if cond3:
raise SomeThirdError()
...
except MyException as err:
print(err)
return ""
edited Nov 15 at 21:16
answered Nov 14 at 13:58
Cartucho
2,15411736
2,15411736
2
@jpp If you raise any subclassed exception you will output the proper message given that you havereturn self.__doc__
in the__str__
method of base class, that's the way sub-classes and inheritance works. I've update the example just to be clear.
– Cartucho
Nov 14 at 14:24
add a comment |
2
@jpp If you raise any subclassed exception you will output the proper message given that you havereturn self.__doc__
in the__str__
method of base class, that's the way sub-classes and inheritance works. I've update the example just to be clear.
– Cartucho
Nov 14 at 14:24
2
2
@jpp If you raise any subclassed exception you will output the proper message given that you have
return self.__doc__
in the __str__
method of base class, that's the way sub-classes and inheritance works. I've update the example just to be clear.– Cartucho
Nov 14 at 14:24
@jpp If you raise any subclassed exception you will output the proper message given that you have
return self.__doc__
in the __str__
method of base class, that's the way sub-classes and inheritance works. I've update the example just to be clear.– Cartucho
Nov 14 at 14:24
add a comment |
up vote
1
down vote
accepted
How about contextmanager
? To alleviate your concern about custom error messages, you can feed a dictionary mapping error classes to messages of your choice.
Since different operations require different errors to be handled, you can use multiple with
statements, feeding different errors as arguments each time.
Here's a contrived example:
from contextlib import contextmanager
@contextmanager
def error_handling(msg, *exceptions):
try:
yield
except exceptions as my_error:
print(msg[my_error.__class__], my_error)
return ''
def do_stuff(d, key, index):
custom_msg = IndexError: 'You have an Index Error!',
KeyError: 'You have a Key Error!'
with error_handling(custom_msg, IndexError, KeyError):
return d[key][index]
# example prints "You have an Index Error! list index out of range"; then returns ''
do_stuff('a': [0, 1, 2], 'a', 10)
add a comment |
up vote
1
down vote
accepted
How about contextmanager
? To alleviate your concern about custom error messages, you can feed a dictionary mapping error classes to messages of your choice.
Since different operations require different errors to be handled, you can use multiple with
statements, feeding different errors as arguments each time.
Here's a contrived example:
from contextlib import contextmanager
@contextmanager
def error_handling(msg, *exceptions):
try:
yield
except exceptions as my_error:
print(msg[my_error.__class__], my_error)
return ''
def do_stuff(d, key, index):
custom_msg = IndexError: 'You have an Index Error!',
KeyError: 'You have a Key Error!'
with error_handling(custom_msg, IndexError, KeyError):
return d[key][index]
# example prints "You have an Index Error! list index out of range"; then returns ''
do_stuff('a': [0, 1, 2], 'a', 10)
add a comment |
up vote
1
down vote
accepted
up vote
1
down vote
accepted
How about contextmanager
? To alleviate your concern about custom error messages, you can feed a dictionary mapping error classes to messages of your choice.
Since different operations require different errors to be handled, you can use multiple with
statements, feeding different errors as arguments each time.
Here's a contrived example:
from contextlib import contextmanager
@contextmanager
def error_handling(msg, *exceptions):
try:
yield
except exceptions as my_error:
print(msg[my_error.__class__], my_error)
return ''
def do_stuff(d, key, index):
custom_msg = IndexError: 'You have an Index Error!',
KeyError: 'You have a Key Error!'
with error_handling(custom_msg, IndexError, KeyError):
return d[key][index]
# example prints "You have an Index Error! list index out of range"; then returns ''
do_stuff('a': [0, 1, 2], 'a', 10)
How about contextmanager
? To alleviate your concern about custom error messages, you can feed a dictionary mapping error classes to messages of your choice.
Since different operations require different errors to be handled, you can use multiple with
statements, feeding different errors as arguments each time.
Here's a contrived example:
from contextlib import contextmanager
@contextmanager
def error_handling(msg, *exceptions):
try:
yield
except exceptions as my_error:
print(msg[my_error.__class__], my_error)
return ''
def do_stuff(d, key, index):
custom_msg = IndexError: 'You have an Index Error!',
KeyError: 'You have a Key Error!'
with error_handling(custom_msg, IndexError, KeyError):
return d[key][index]
# example prints "You have an Index Error! list index out of range"; then returns ''
do_stuff('a': [0, 1, 2], 'a', 10)
answered Nov 11 at 16:02
jpp
87.3k194999
87.3k194999
add a comment |
add a comment |
up vote
1
down vote
How about to define a function that has a dictionary contained the whole errors and responses. in this case you can catch an exception one time and send it to a handler
UPDATE :
def handle (e) :
exp = 'IOError' : 'NO such a file in dir ...! ' ,
'KeyboardInterrupt' : 'Exiting ... (Keyboard interruption)',
'IndexError' : ' a sequence subscript is out of range' ,
'NameError' : 'a local or global name is not found'
for key , value in exp.items() :
if e == key :
print (value) #or do whatever you want
def test() :
try :
f = open('no-file' , 'r')
except Exception as e :
handle (type(e).__name__)
if __name__ == "__main__" :
test()
Probably goes without saying, but the...
bit is relevant here, it would be helpful if you can fill them in with a trivial example users can run.
– jpp
Nov 14 at 14:16
you're right, I hope this helps.
– Ali Kargar
Nov 14 at 18:41
add a comment |
up vote
1
down vote
How about to define a function that has a dictionary contained the whole errors and responses. in this case you can catch an exception one time and send it to a handler
UPDATE :
def handle (e) :
exp = 'IOError' : 'NO such a file in dir ...! ' ,
'KeyboardInterrupt' : 'Exiting ... (Keyboard interruption)',
'IndexError' : ' a sequence subscript is out of range' ,
'NameError' : 'a local or global name is not found'
for key , value in exp.items() :
if e == key :
print (value) #or do whatever you want
def test() :
try :
f = open('no-file' , 'r')
except Exception as e :
handle (type(e).__name__)
if __name__ == "__main__" :
test()
Probably goes without saying, but the...
bit is relevant here, it would be helpful if you can fill them in with a trivial example users can run.
– jpp
Nov 14 at 14:16
you're right, I hope this helps.
– Ali Kargar
Nov 14 at 18:41
add a comment |
up vote
1
down vote
up vote
1
down vote
How about to define a function that has a dictionary contained the whole errors and responses. in this case you can catch an exception one time and send it to a handler
UPDATE :
def handle (e) :
exp = 'IOError' : 'NO such a file in dir ...! ' ,
'KeyboardInterrupt' : 'Exiting ... (Keyboard interruption)',
'IndexError' : ' a sequence subscript is out of range' ,
'NameError' : 'a local or global name is not found'
for key , value in exp.items() :
if e == key :
print (value) #or do whatever you want
def test() :
try :
f = open('no-file' , 'r')
except Exception as e :
handle (type(e).__name__)
if __name__ == "__main__" :
test()
How about to define a function that has a dictionary contained the whole errors and responses. in this case you can catch an exception one time and send it to a handler
UPDATE :
def handle (e) :
exp = 'IOError' : 'NO such a file in dir ...! ' ,
'KeyboardInterrupt' : 'Exiting ... (Keyboard interruption)',
'IndexError' : ' a sequence subscript is out of range' ,
'NameError' : 'a local or global name is not found'
for key , value in exp.items() :
if e == key :
print (value) #or do whatever you want
def test() :
try :
f = open('no-file' , 'r')
except Exception as e :
handle (type(e).__name__)
if __name__ == "__main__" :
test()
edited Nov 14 at 18:40
answered Nov 13 at 16:45
Ali Kargar
1544
1544
Probably goes without saying, but the...
bit is relevant here, it would be helpful if you can fill them in with a trivial example users can run.
– jpp
Nov 14 at 14:16
you're right, I hope this helps.
– Ali Kargar
Nov 14 at 18:41
add a comment |
Probably goes without saying, but the...
bit is relevant here, it would be helpful if you can fill them in with a trivial example users can run.
– jpp
Nov 14 at 14:16
you're right, I hope this helps.
– Ali Kargar
Nov 14 at 18:41
Probably goes without saying, but the
...
bit is relevant here, it would be helpful if you can fill them in with a trivial example users can run.– jpp
Nov 14 at 14:16
Probably goes without saying, but the
...
bit is relevant here, it would be helpful if you can fill them in with a trivial example users can run.– jpp
Nov 14 at 14:16
you're right, I hope this helps.
– Ali Kargar
Nov 14 at 18:41
you're right, I hope this helps.
– Ali Kargar
Nov 14 at 18:41
add a comment |
This is a very broad question. Exception handling is very specific to the use cases involved, and it could well be that your actual application could avoid a bunch of exceptions altogether if restructured. But with the overly generic
Something..Error
exceptions here withdo something
code there is only very broad advice we can give. Context managers could help, but are not a general fits-all solution. Catching a base exception is another. Usingexcept (Exc1, Exc2, Exc3)
then dispatching from there in the exception handler is a 3rd. These all have different characterstics.– Martijn Pieters♦
Nov 17 at 17:30
But writing all that down is going to require something approaching publishable book status, so I've closed this as Too Broad.
– Martijn Pieters♦
Nov 17 at 17:30