Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception in python unknown errors

Tags:

python

      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

like image 417
user2933455 Avatar asked Aug 24 '26 17:08

user2933455


2 Answers

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.

like image 132
Martijn Pieters Avatar answered Aug 27 '26 08:08

Martijn Pieters


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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!