Java best practices when throwing exceptions: throwing core Java exceptions

后端 未结 5 1146
南方客
南方客 2021-02-02 09:07

Instead of throwing new Exception(\"Some message\", maybeSomeCause), which means that all callers of my method will need to catch Exception (which can include Runti

5条回答
  •  失恋的感觉
    2021-02-02 09:18

    The lists provided in your question are not very usable as quick-reference material, and most descriptions in the dev docs seem cryptic to me.

    I haven't run across any short-ish lists of the most reusable built-in exceptions. I've done my best to create one below, but I'm sure it is far from perfect.

    github gist link (or see current content below)

    List of Potentially Reusable Built-in Exceptions

    organized by estimated utility

    IllegalArgumentException

    Thrown to indicate that a method has been passed an illegal or inappropriate argument.

    IndexOutOfBoundsException

    Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

    ArithmeticException

    Thrown when the requested mathematical operation is non-sensical or impossible. example: int x = 1/0;

    IllegalStateException

    The application is not in an appropriate state for the requested operation. example: trying to save before file is loaded or created.

    DataFormatException

    Throw this when you have recieved improperly formatted data. example: MyClass.applyJSONString("{non:sense,all,garbled=definitely.not;json{{{")

    TimeoutException

    Throw this if something took too long and you're giving up.

    KeySelectorException

    I think it makes sense to throw this if you are trying to looking for an object using a key and it was not found or the key is otherwise invalid, but I don't really understand the dev docs on it.

    example: myDataStructure.get("lookup_key"); when lookup_key is not in the data structure.

    IOException

    Having some problem reading/writing? Throw this exception.

    ScriptException

    Running a script of some form and found a problem with it (not I/O or parsing)? Throw this exception.

    GeneralSecurityException

    Throw this if you encounter a security-related issue.

    RuntimeException

    Use this for some runtime-error that doesn't fit well into any other category.

提交回复
热议问题