Difference Between Throw and Throws
Keyword
throw
throw is a keyword in java language which is used to
throw any user defined exception to the same signature of method in which the
exception is raised.
Note: throw keyword always
should exist within method body.
whenever method body contain throw keyword than the call
method should be followed by throws keyword.
Syntax
class className
{
returntype method(...) throws Exception_class
{
throw(Exception obj)
}
}
throws
throws is a keyword in java language which is used to
throw the exception which is raised in the called method to it's calling method
throws keyword always followed by method signature.
Example
returnType methodName(parameter)throws
Exception_class....
{
.....
}
Difference between throw and throws
throw
|
throws
|
|
1
|
throw is a keyword used for hitting and generating the
exception which are occurring as a part of method body
|
throws is a keyword which gives an indication to the
specific method to place the common exception methods as a part of try and
catch block for generating user friendly error messages
|
2
|
The place of using throw keyword is always as a part of
method body.
|
The place of using throws is a keyword is always as a
part of method heading
|
3
|
When we use throw keyword as a part of method body, it
is mandatory to the java programmer to write throws keyword as a part of
method heading
|
When we write throws keyword as a part of method
heading, it is optional to the java programmer to write throw keyword as a
part of method body.
|
Example of throw and throws
Example
// save by DivZero.java
package pack;
public class DivZero
{
public void division(int
a, int b)throws ArithmeticException
{
if(b==0)
{
ArithmeticException ae=new
ArithmeticException("Does not enter zero for Denominator");
throw ae;
}
else
{
int c=a/b;
System.out.println("Result: "+c);
}
}
}
Compile:
javac -d . DivZero.java
Example
// save by ArthException.java
import pack.DivZero;
import java.util.*;
class ArthException
{
public static void
main(String args[])
{
System.out.println("Enter any two number:
");
Scanner s=new Scanner(System.in);
try
{
int a=s.nextInt();
int b=s.nextInt();
DivZero dz=new DivZero();
dz.division(a, b);
}
catch(Exception e)
{
System.err.println(e);
}
}
}
Compile:
javac ArthException.java
Steps to Compile and Run code
First you save throw-example files into you PC in any
where, here i will save this file in C:\>
·
C:\throw-example\>javac
-d . DivZero.java
·
C:\throw-example\>javac
ArthException.java
Note: First compile
DivZero.java code then compile ArthException.java code
0 comments:
Post a Comment