The throw keyword in Java is utilized to explicitly throw an exception from a strategy or any block of code. We can throw either checked or unchecked exception. The throw keyword is mostly used to throw custom exceptions.
The flow of execution of the program stops following the throw articulation is executed and the closest encasing try block is verified whether it has a catch proclamation that coordinates the kind of exception. On the off chance that it finds a match, controlled is exchanged to that announcement generally next encasing try block is checked, etc. In the event that no coordinating catch is discovered, at that point the default exception handler will stop the program.
Java Program To Implement Throw Statement
import java.util.Scanner;
class ThrowsStatement
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] a = new int[5];
System.out.print("Enter 5 numbers : ");
for(int i=0;i<5;i++)
a[i] = sc.nextInt();
try
{
access(a);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Out Of Bounds Exception : " + e);
}
}
static void access(int[] a) throws ArrayIndexOutOfBoundsException
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the index of element : ");
int x = sc.nextInt();
System.out.println("Element is : " + a[x]);
}
The flow of execution of the program stops following the throw articulation is executed and the closest encasing try block is verified whether it has a catch proclamation that coordinates the kind of exception. On the off chance that it finds a match, controlled is exchanged to that announcement generally next encasing try block is checked, etc. In the event that no coordinating catch is discovered, at that point the default exception handler will stop the program.
Java Program To Implement Throw Statement
import java.util.Scanner;
class ThrowsStatement
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] a = new int[5];
System.out.print("Enter 5 numbers : ");
for(int i=0;i<5;i++)
a[i] = sc.nextInt();
try
{
access(a);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Out Of Bounds Exception : " + e);
}
}
static void access(int[] a) throws ArrayIndexOutOfBoundsException
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the index of element : ");
int x = sc.nextInt();
System.out.println("Element is : " + a[x]);
}
OUTPUT :
Enter 5 numbers : 1 2 3 4 5
Enter the index of element : 9
Array Index Out Of Bounds Exception : java.lang.ArrayIndexOutOfBoundsException : 9
tags : java , java code , java tutorialspoint , tutorialspoint , throw statement , code , code hour , code camp
tags : java , java code , java tutorialspoint , tutorialspoint , throw statement , code , code hour , code camp