• Different types of exceptions in Java

    Different types of exception

    All exception types are subclass of a built-in class Throwable is at the top of the exception class hierarchy. Immediately below Throwable there are two subclasses that partition exception into two distinct branches. One branch is headed by exception, this class is used for exceptional conditions that user’s program should catch. This is also the class that we will subclass to create our own custom exception types. There is an important subclass of exception called runtime exception. Exceptions of this type are automatically defined for the programs that we write and includes exception class such as:

    •  ArrayIndexOutOfBoundsExceptions
    • MalformedURLException
    •  SQLIntegrityConstraintViolationException

    The other branch is headed by Error which defines exception that are not expected to be caught under normal circumstances by our program. Exception of type Error are used by the Java runtime system to indicate errors having to do with Java runtime environment itself. Stack overflow is an example of such an error.
    Error exceptions typically created in response to catastrophic failures that can’t be usually handled by our program.

    Is it possible to create your own Exception?

    Although Java’s built in exceptions handle most common errors we may want to create our own exception types to handle situations specific to our applications. This is achieved just by defining a subclass of Exception. Our subclass doesn’t need to actually implement anything. It’s their existence in the type system. The type system that allows us to use them as exceptions.

     Example:

    class NegNumExceptions extends Exception
    {
    public String toString()
    {
    System.out.print(“Negative Numbers not allowed”);
    }
    }
    class Num
    {
    public static void main(String args[]) throws NegNumException
    {
    int a=-7;
    if(a<0)
    {
    throw NegNumException();
    }
    }
    }

  • You might also like

    No comments:

    Post a Comment

search topics

NEWSLETTER

Get All The Latest Updates Delivered Straight Into Your Inbox For Free!