except ValueError:
print "the input is Invaild(dd.mm.year)"
except as e:
print "Unknown error"
print e
This is the code I wrote, if an error different then valueerror will happen will it print it in e? thanks
3 Answers 3
You'll need to catch the BaseException or object here to be able to assign to e:
except ValueError:
print "the input is Invaild(dd.mm.year)"
except BaseException as e:
print "Unknown error"
print e
or, better still, Exception:
except ValueError:
print "the input is Invaild(dd.mm.year)"
except Exception as e:
print "Unknown error"
print e
The blanket except: will catch the same exceptions as BaseException, catching just Exception will ignore KeyboardInterrupt, SystemExit, and GeneratorExit. Not catching these there is generally a good idea.
For details, see the exceptions documentation.
6 Comments
Exception also ignore SyntaxError?SyntaxError is a subclass of Exception.Exception, because in general I wouldn't want to catch a syntax error in a try statement.try doesn't apply yet. Only when you use import, eval, exec or compile() can you catch SyntaxError exceptions.SyntaxError in an eval (for example) so I see the logic now. Again, many thanks for your excellent answers!No, that code will throw a SyntaxError:
If you don't know the exception your code might throw, you can capture for just Exception. Doing so will get all built-in, non-system-exiting exceptions:
except ValueError:
print "the input is Invaild(dd.mm.year)"
except Exception as e:
print "Unknown error"
print e
Comments
You can access the Error Type in python3 using type().__name__
e.g.
try:
...
except Exception as err:
print(f'Error: {str(err)}, Type: {type(err).__name__}')
...
...