Throw
We can throw any exception by using the throw keyword.
Throw can also be used for throwing custom exceptions.
Throw is used inside the method or constructor to throw the exception from method.
We cannot handle checked Exception with throw Keyword
Multiple Exceptions cannot be thrown by using Throw kayword
The exception occur that should be a subclass of Throwable class.
Syntax-
public void methodName()
{
//throwing an exception
throw new nameofException("display");
}
Program with Throw keyword:-
import java.util.Scanner;
class Test1
{
public int divideValues()
{
Scanner src=new Scanner(System.in);
System.out.println("Enter the value of a:");
int a=src.nextInt();
System.out.println("Enter the value of b:");
int b=src.nextInt();
int c=a/b;
if (b == 0)
{
throw new ArithmeticException("Divider should not be equal to zero..");
}
System.out.println("The result is: "+c);
return c;
}
public static void main(String args[])
{
Test1 obj=new Test1();
obj.divideValues();
}
}
OutPut:-
Enter the value of a:
12
Enter the value of b:
3
The result is: 4
Program when we enter the (b)2nd value 0:-
import java.util.Scanner;
class Test1
{
public int divideValues()
{
Scanner src=new Scanner(System.in);
System.out.println("Enter the value of a:");
int a=src.nextInt();
System.out.println("Enter the value of b:");
int b=src.nextInt();
int c=a/b;
if (b == 0)
{
throw new ArithmeticException("Divider should not be equal to zero..");
}
System.out.println("The result is: "+c);
return c;
}
public static void main(String args[])
{
Test1 obj=new Test1();
obj.divideValues();
}
}
OutPut:-
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test1.divideValues(TryProgram.java:11)
at Test1.main(TryProgram.java:23)
Throws
Throws keyword used with the method signature to declare list of exceptions that may occur during the method execution.
It is not used to throw the exceptions.
Checked Exception can be handle with throw Keyword.
Multiple Exceptions canbe thrown by using Throws kayword.
We must handle the throws exceptions with try-catch block.
Syntax-
public void methodName()throws ArithmeticException,SQLException
{
//method code
}
Program1 when we enter the (b)2nd value 0:-
class Test1
{
void Divide() throws ArithmeticException
{
int x=25,y=0,result;
result = x / y;
System.out.println("The result is : " + result);
}
public static void main(String[] args)
{
Test1 obj = new Test1();
try
{
obj.Divide();
}
catch(ArithmeticException Ex)
{
System.out.println(Ex.getMessage());
}
System.out.println("Rest of the Program...");
}
}
OutPut:-
/ by zero
Rest of the Program...