Java Program to use Catch to Handle the Exception
Last Updated :
10 Aug, 2022
The exception is the event occurs when the program is executing. Due to this exception, the normal flow of the program will get disrupts. Whenever an exception occurs in the method, the method creates an object and sends that object to the runtime system. For example, the file needs to be open is not found, class not found exception, Arithmetic Exception, SQL Exception, etc.
To handle these exceptions there are 4 standard techniques:
- Try-catch
- Throw
- Throws
- Using HandlerExceptionResolver interface (Only in Spring-framework)
Catch usage is described here below:
Syntax:
try {
// Put the code in the try block which may occur any
// kind of exception
}
catch (ExceptionName e) {
// handle the exception
}
There are two examples discussed below:
- Using predefined exception Class
- Using defining own exception Class
Example 1: Usage of catch with a predefined exception class
This is an example of a predefined exception which is handled by try and catch block.
Java
import java.io.*;
import java.util.*;
import java.util.Scanner;
class GFG {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println( "Enter the first number" );
Integer number1 = input.nextInt();
System.out.println( "Enter the second number" );
Integer number2 = input.nextInt();
try {
int result = number1 / number2;
System.out.println( "Result is " + result);
}
catch (ArithmeticException e) {
System.out.println( "Dividing by zero" );
}
}
}
|
Output:
Example 2: Usage of catch by defining the exception class
In this example, the exception is user-defined in which exception class is written as follows:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println( "Enter the name" );
String name = input.next();
try {
System.out.println( "Enter the age" );
Integer age = input.nextInt();
if (age <= 18 ) {
MyException me = new MyException();
throw me;
}
else
{
System.out.println( "name:" + name);
System.out.println( "age:" + age);
}
}
catch (MyException e)
{
System.out.println(e);
}
}
}
class MyException extends RuntimeException {
public String toString()
{
return "Age must be greater than 18" ;
}
}
|
Input 1:
Enter the name : Geek
Enter the age: 18
Output:
Age must be greater than 18 // Age is equal to 18 so the exception is occurred
Input 2:
Enter the name : Geek
Enter the age: 20
Output:
name: Geek
age:20 // Age is greater than 18 so no exception.
Share your thoughts in the comments
Please Login to comment...