Exception other than RuntimeException

前端 未结 3 562
臣服心动
臣服心动 2020-11-30 15:27

Is there any possibility of exceptions to occur other than RuntimeException in Java? Thanks.

3条回答
  •  野性不改
    2020-11-30 16:10

    Yes, there are Three kinds.

    Checked exceptions

    The compiler will let you know when they can possible be thrown, due to a failure in the environment most likely.

    They should be caught, if the program can do something with it, otherwise it is preferred to let them go.

    Most of them inherit from

    java.lang.Exception
    

    or from

    java.lang.Throwable
    

    Although it is better to inherit from the former.

    For example:

    java.io.IOException
    

    Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.

    Errors

    These are special kinds of exceptions. They SHOULD NOT BE CAUGHT for when they occur means that something really really bad just happened.

    All of them inherit from

    java.lang.Error
    

    For example:

    java.lang.OutOfMemoryError
    

    Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

    or

    java.lang.StackOverflowError
    

    Thrown when a stack overflow occurs because an application recurses too deeply.

    RuntimeExceptions

    Used to identify programmer failures, rather than resource failures.

    A Runtime exception could "normally" be avoided while coding. If you have one most likely you're doing something wrong.

    Sometimes runtime exceptions are caught, but, unless you know exactly what you're doing and why, catching them is a bad practice ( again, unless that's exactly what you need )

    They inherit from

    java.lang.RuntimeException 
    

    For example

    java.lang.ArrayIndexOutOfBoundsException
    

    Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array

    or

    java.lang.NullPointerException
    

    Thrown when an application attempts to use null in a case where an object is required

    About the last two, MOST of the times, they can be avoided by programming carefully and understand what the state of the program is ( does this array have 5 elements? why should I try to access -1 or 6th. Is this reference null? why should I call null.toString() )

    Although I have had arguments with guys that claim that all NPE should be caught. Well what can I say.

提交回复
热议问题