I am original Java developer, for me, checked Exception in Java is obviously/easy enough for me to decide to catch or throw it to the caller to handle later. Then it comes Python, there is no checked exception, so conceptually, nothing forces you to handle anything(In my experience, you don't even know what exceptions are potentially thrown without checking the document). I've been hearing quite a lot from Python guys that, in Python, sometimes you better just let it fail at runtime instead of trying to handle the exceptions.
Can someone give me some pointers regarding to:
what's the guideline/best practice for Python Exception Handling?
what's the difference between Java and Python in this regard?
Python exception performs exception handling a bit different from Java, but the syntax is similar. In Java, an exception is thrown in code whereas Python does not throw exceptions, but instead it raises the exceptions.
Also, list the optional clauses for a “try-except” block in Python? The except, else, and finally clauses are optional, though every try must have at least one of those clauses. Java does not have an else clause, which is run when no exception occured.
When opting for a starting point, you should take your goals into account. Java is popular among programmers interested in web development, big data, cloud development, and Android app development. Python is favored by those working in back-end development, app development, data science, and machine learning.
In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.
OK, I can try and give an answer which I'll keep as neutral as it can be... (note: I have done Python professionally for a few months, but I am far from mastering the language in its entirety)
The guidelines are "free"; if you come from a Java background, you will certainly spend more time than most Python devs out there looking for documentation on what is thrown when, and have more try
/except
/finally
than what is found in regular python code. In other words: do what suits you.
Apart from the fact that they can be thrown anywhere, at any moment, Python has multi-exception catch (only available in Java since 7), with
(somewhat equivalent to Java 7's try-with-resources), you can have more than one except
block (like Java can catch
more than once), etc. Additionally, there are no real conventions that I know of on how exceptions should be named, so don't be fooled if you see SomeError
, it may well be what a Java dev regards as a "checked exception" and not an Error
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With