• Difference between throw and throws in Java

    Significance of using throw keyword

    Java allows catching exceptions that are thrown by Java runtime system. However it’s possible for our program to throw an exception explicitly using throw statement. General form of throw statement is as follows:
     throw ThrowableInstance

    Here throwable instance must be an object of type throwable or a subclass of throwable. Primitive types int or char as well as non throwable classes such as String and Object cannot be used as exceptions. The flow of executions stop immediately after the throw statement. Any subsequent statement are not executed and the nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it doesn’t find match control is transferred to that statement, if not then the next enclosing try statement is inspected and so on. If no matching catch is found then the default exception handler halts the program and print the stack trace.


    Significance of using throws keyword

    If a method is capable of causing an exception that it doesn’t handle, then it must specify this behaviour. So that callers of the method can guard themselves against the exception. We do this by including a throws clause in the methods declaration. A throws clause lists the type of exceptions that a method might throw. This is necessary for all exceptions except those of type error or runtime exception or any of their subclasses. General form of throws clause is as follows:

    type method-name(parameter list) throws Exception list
    {
    // Body of the method
    }

    Here exception list is a comma separated list of exceptions that a method can throw.


     Difference of throw and throws.

    • Use:

    throw keyword is used to explicitly throw an exception whereas throws is used in those cases where a method is capable of causing an exception that it doesn’t handle.

    • General Form:

    General form of throw statement is throw ThrowableInstance

    Whereas throws has the general form as follows:
    type method-name(parameter list) throws Exception list
    {
    // Body of the method
    }
  • You might also like

    No comments:

    Post a Comment

search topics

NEWSLETTER

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