Recent

3.throw and throws keywords

throw and throws Keywords – Exception Handling


throw Keyword
“throw” keyword is used to throw an exception in methods, All the methods use throw keyword to throw an exception. The throw keyword is mainly used to throw custom exception. The “throw” statement requires a single argument: a throwableobject. Throwable objects are instances of any subclass of the Throwable class. Here’s an example of a “throw” statement.
> throw SomeException

Example: throw keyword example
In this example we have created a method get(inta) that takes an integers as a argument. If the age found to be less than  18, we are throwing an exception.


class Temp
{
int age;

void get(int age)
{
    if(age<18)
    {
        try
        {
        throw new ArithmeticException("Invalid Age");
        }
        
        catch(ArithmeticException e)
        {
        System.out.println(e);
        }
    }
    else
        {
        this.age = age;
                System.out.println("Valid age");
        }
}

public static void main(String[] s)
{
Temp t = new Temp();
t.get(10);
}}

/*Output
java.lang.ArithmeticException: Invalid Age
*/

throws Keyword
throws Keyword is used to make the program handler free.
·         Suppose same function is defined by the developers which is used by the programmer directly, So most of the time developed function does not have handler for exception.
·         So to show that whether handler is there or not, both programmer and developer use “throws” keyword. Thus by printing appropriate message programmer knows if handler is there or not.

Advantages of throws:
·         Used to make program handler free.
·         Used to give indication to the end user.
·         We can also use throws for more than one exception but that is not preferred usually.
·         Throws keyword also used for forwarding the exception in a calling chain. Thus JVM terminate the program, by U-Turn which we do not want and thus throws uses avoid.
For Example: Using “throws” keyword


class Temp
{

//throws exception
public static void main(String[] s)throwsArithmeticException
{
int x = 10/s.length;  //this line will cause arithmetic exception
System.out.println(x); //and we are writing this line without handler
}
}

/*Output
Exception in thread "main"java.lang.ArithmeticException: / by zero
        at Temp.main(Temp.java:7)
*/

No comments:

Post a Comment

Bug-dbug Designed by Bugdbug - Developed by Belson Raja Copyright © 2016

Theme images by Bim. Powered by Blogger.
Published By Bugdbug India