I'm pretty new to Python overall however I know Java pretty well.
I am trying to use the exceptions in Python but I'm not quite sure how they work.
In Java I would do this:
try {
//Code inside
} catch (Exception e) {
continue;
}
How would I do something like this in Python?
Thanks!
CodePudding user response:
While your own solution is correct Python, it is not quite the equivalent of the given Java code. Python's bare except
catches all throwables (which extend from BaseException
in Python), not just all exceptions. This includes things like KeyboardInterrupt
(called by Ctrl C) and SystemExit
, which should almost never be caught.
The solution is to be as narrow as possible in defining the exception you catch. For instance, if you're converting a string to an integer but it might not be numeric, catch ValueError
:
try:
converted = int(string)
except ValueError:
# handle the error
If you really want to catch any exception, use except Exception:
rather than bare except:
.
CodePudding user response:
All good I think I got it!
I can just use
try:
#code here
except:
continue