throw
throw is used to throw an exception explicitly.
throw is used in method implementation.
throw is followed by an instance.
we can throw only single exception at a time.
Syntax:
throw new exception_name;
throw new exception_name;
Example:
public class ThrowExample{
void check(int num){
if(num%2==0)
{
System.out.println("EVEN
NUMBER");
}
else
{
throw new ArithmeticException("NOT
EVEN");
}
public static void main(String args[]){
ThrowExample t1=new ThrowExample();
t1.check(12);
}
}
Output:
// t1.check(12);
So output is
EVEN NUMBER
// t1.check(13);
So output is
Exception in
thread "main" java.lang.ArithmeticException: NOT EVEN
at
ThrowExample.check(ThrowExample.java:8)
at
ThrowExample.main(ThrowExample.java:12)
Command exited
with non-zero status 1
throws
throws is used to declare an exception.
throws is used in method signature.
throws is followed by class
throws can declare multiple exception at a time like
Syntax:
return_type method_name() throws exception_class_name
{
//
}
Example:
import java.io.*;
public class ThrowsExample{
void Show()throws
IOException{
System.out.println("Welcome to LearningPoint92");
}
}
public static void
main(String args[])throws IOException{
ThrowsExample
t1=new ThrowsExample();
t1.Show();
}
}
Output:
Welcome to LearningPoint92
No comments:
Post a Comment