Exceptions in Java

Hierarchy of exceptions

Exceptions are divided into several classes, but they all have a common ancestor - the Throwable class, of which the Exception and Error classes are descendants.

Errors are more serious problems that, according to the Java specification, should not be handled in a native program, as they are related to JVM-level problems. For example, exceptions of this kind arise if the memory available to the virtual machine runs out.

Exceptions are the result of problems in the program that are, in principle, solvable, predictable, and the consequences of which can be eliminated within the program. For example, an integer was divided by zero.

Checked and unchecked exceptions

In Java, all exceptions are of two types:

  • checked must be handled by a catch block or described in the method signature (for example, throws IOException). The presence of such a signature handler/modifier is checked at compile time;
  • unchecked, which include Error errors (for example, OutOfMemoryError), which are not recommended to handle, and runtime exceptions introduced by the RuntimeException class and its descendants (for example, NullPointerException), which may not be handled by a catch block and not described in the method signature.

Operator throw allows you to force an exception to be thrown:

throw new Exception();

The throws modifier is written in the method signature and indicates that the method can potentially throw an exception of the specified type.

To write custom exception you must inherit from the base class of the required type of exception (for example, Exception or RuntimeException).

class CustomException extends Exception {
    public CustomException() {
        super();
    }

    public CustomException(final String string) {
        super(string + " is invalid");
    }

    public CustomException(final Throwable cause) {
        super(cause);
    }
}

What are the unchecked exceptions?

Most common: ArithmeticException, ClassCastException, ConcurrentModificationException, IllegalArgumentException, IllegalStateException, IndexOutOfBoundsException, NoSuchElementException, NullPointerException, UnsupportedOperationException.


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed