Python, Java, C++ exception handling, a comparison


1. TL;DR: What happened?

I mess up all the time when I code, I’ve always wanted to do a more rigorous session on exceptions and error handling between I want to compare exception handling in three languages, P

2. Resources

3. Overview of Throwable and Exception Class Hierarchies from Python and Java

Java class hierarchy from "Throwable".source

In Java, there is a difference between Exception and Error, as they are taken to mean different things.

  • Exception: User program should catch. It is further subdivided into two kinds
    • Checked Exception: The compiler will force you to handle the exception, or else the program will not compile. Checked exceptions is intended to represent problems outside the control of the program.
    • Unchecked Exception: The compiler will not force you to the handle the exception. Unchecked exceptions is intended to cover programming problems. As such, they are not document in a method’s API, since there are innumerable ways in which one can cause an unchecked exception. The official Java documentation specifically warns against throwing unchecked exceptions because of laziness for specifying the correct checked exception.
  • Error: User program should not catch. Thrown by JVM. Assertion, StackOverflow, etc.
Python's class hierarchy from "BaseException"source
  • In Python, Error and Exception do not carry the same meaning as Java. For example, StackOverflowError in Python is, as seen above, a sub-class of RuntimeError, which is itself a sub-class of Exception.
  • Classes which are derived from BaseException but not Exception all relate to some kind of intented stop/calling of exit(), stop().

Best practices compared

Try… Catch… Finally Usage

Creating Your Own Exception Class

The Python documentation warns against exception BaseException. Rather, Exceptions should be extending Exception.
Under Construction


Author: Zhao Du
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source Zhao Du !
 Previous
自動微分とプログラミングの関係についての理解を深めましょう! 自動微分とプログラミングの関係についての理解を深めましょう!
DLフレームワークを使うと、 「コンパイルされたグラフ」、「ダイナミックなグラフ」のような言葉がよく見られている。このポストでそういう表現の後ろの理由・詳細を探してみたいと思います。
2021-09-07
Next 
alphafoldを一から解説 alphafoldを一から解説
生化学の背景から注意力に基づくメカニズムまでAlphaFoldの理解を深めましょう!
2021-08-11
  TOC