Java Exception handling using throws

If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method's declaration. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions,except those of type Error or Run time Exception, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result.
This is the general form of a method declaration that includes a throws clause:

type method-name(parameter-list) throws exception-list

{
// body of method
}

Here, exception-list is a comma-separated list of the exceptions that a method can throw. Following is an example of an incorrect program that tries to throw an exception that it does not catch. Because the program does not specify a throws clause to declare this fact, the program will not compile.

Program

class Number
{
    private int num;
    public void accept(int n) throws Exception
    {
        if( n == 0 )
        {
        throw new Exception("can’t assign zero…");
        }
        else if(n < 0)
        {
        throw new Exception("can’t assign -ve value…");
        }
        else
        {
        System.out.println("Valid value.");
        num = n;
        }
    }
}
public class ThrowsDemopgm
{
    public static void main(String args[])
        {
        Number ob = new Number();
        try
          {
          ob.accept(-8);

                  }
        catch(Exception e)
          {
                  System.out.println(" Error: " + e);
           System.out.println("");
           }
        }
}
Output

Error java.lang.Exception: can't assign -ve value


Java Exception handling using throws

0 comments:

Post a Comment

 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org