Throw clause Java Example Program
Syntax
if(<Condition>){
throw new <ExceptionName>("Exception Statement");
}
Throw clause Example Program
public class ThrowClause {
//Throw exception if number 1 is greater than 900
static int add(int num1, int num2){
if (num1 > 900){
throw new ArithmeticException("Num 1 is greater than 900 and hence Exception is thrown");
}else{
System.out.println("Both parameters are correct!!");
}
return num1+num2;
}
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number 1 : ");
int num1 = scanner.nextInt();
System.out.println("Enter number 2 : ");
int num2 = scanner.nextInt();
int result=add(num1,num2);
System.out.println("Result is : "+result);
}
}
Sample Output 1
Enter number 1 :
1000
Enter number 2 :
700
Exception in thread "main" java.lang.ArithmeticException: Num 1 is greater than 900 and hence Exception is thrown
at learnjavaprograms.ThrowClause.add(ThrowClause.java:18)
at learnjavaprograms.ThrowClause.main(ThrowClause.java:30)
Java Result: 1
Sample Output 2
Enter number 1 :
100
Enter number 2 :
200
Both parameters are correct!!
Result is : 300
Exception Handling Programs
- Exception Handling Example Java Program
- Nested Try Example Java Program
- Throw clause Java Example Program
- Throws clause Java Example Program
- Finally Block Java Example Program
- Try-Catch-Finally Java Example Program
- Pass Argument while throwing Exception Java Example Program
- Multiple Catch Blocks Java Example Program
- Re-Throw Exception Java Example Program
- Print stack trace of the Exception Java Example Program
- Handle Exception without Catch block Java Example Program
- Custom Exception Java Example program
- Termination of Program Due To Unhandled Exception Java Example Program
- Divide by Zero Java Example Program
- Null Pointer Exception Java Example Program
- ArrayIndexOutOfBounds Exception Java Example Program
- Number Format Exception Java Example Program
- String Index Out Of Bounds Exception Java Example Program
- ParseException Java Example Program
Read More Articles
- Multiple Inheritance Using Interface Example Java Program
- Single Inheritance Example Java Program
- Multilevel Inheritance Example Java Program
- Hierarchical Inheritance Example Java Program
- Find all Substrings of a given string Example Java Program
- Create Matrix Example Java Program
- Sum Of Three Numbers Example Java Program
- Heap Sort Example Java Program
- Twin Prime Example Java Program
- Compile Time Polymorphism Example Java Program