What is the package? What is the difference between throw and throws keywords?

Ram Pothuraju
Packages are the containers for the classes that are used to keep the class name space compartmentalized. Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.
     To create the packages use the “package” command as follows:
     package p1;
Here p1 is name of the package and we insert the package p1 in the program with the import statements as follows:
     import p1;

Some packages are
i)                    import java.awt.*;
ii)                   import java.awt.event.*;
iii)                 import java.applet.*;



            throw:


            User can catching exceptions that are thrown by the Java run – time system. However, it is possible for program to throw an exception explicitly, using the throw statement. The general form of throw is shown here:
                        throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. There is two ways obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator.
            The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.

            Class bug extends Exception
            {
            ………//statement
}         
            ……
…….
                                    int i=10;
                                    try
{
            if(i<12) throw new OutOfRange();
}catch(OutOfRange e)
{
            …….//statement
}



            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. We do this by including a throws clause in the method declaration. A throw clause lists the types of exception that a method might throw. This is necessary for all exception, except those of type Error or RuntimeException 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.
            type method – name (parameter list) throws exception list
            {
            // body of the mewthod

}
Tags

Post a Comment

0Comments

Post a Comment (0)