throw
keyword is used in Java to explicitly create and throw an exception object.
throws
or handle it with try-catch
.
throw throwableObject;
throwableObject
is an instance of the Throwable
class or its subclass (like Exception
or Error
).
throw new ArithmeticException("You cannot divide by zero");
ArithmeticException ae = new ArithmeticException("You cannot divide by zero");
throw ae;
import java.util.Scanner;
public class ThrowDemo
{
void m1()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter no1");
int no1 = sc.nextInt();
System.out.println("Enter no2");
int no2 = sc.nextInt();
try
{
int res = no1/no2;
System.out.println("Result : "+res);
}
catch (Exception e)
{
System.out.println("Exception caught: " + e.getMessage());
}
}
public static void main(String[] args)
{
ThrowDemo td = new ThrowDemo();
td.m1();
}
}
Enter no1 100 Enter no2 0 Exception caught: / by zero
main()
in this case).
main()
also doesn't handle it either, the exception will propagate to the JVM.
Exception
. In real applications, it is better to throw specific exception types.
throw
keyword.
throw
keyword creates only a single exception object at a time, not multiple.
throw
keyword, only exception object can be thrown, not classes or literals.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.