Exception Handling
Exception In Java
An error will occur when there is wrong user input, e.g., user-entered alphabet where a number is needed
. You can see the long message. You can use try-catch to catch the error and perform your task when the exception occurs.
Syntax Of Try Catch
try {
// Code to try
}
catch(Exception e) {
// Code to Handle Error
}
Basic Java Program
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your birth year: ");
int birthyear = sc.nextInt();
int age = 2022 - birthyear;
System.out.println("Your age is "+age);
}
}
In this program, an error will be shown if you enter alphabets instead of a number.
Same Program With Try Catch
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your birth year: ");
try{
int birthyear = sc.nextInt();
int age = 2022 - birthyear;
System.out.println("Your age is "+age);
}catch (Exception ex){
System.out.println("Error make sure input is correct.");
}
}
}
Finally
It can execute code regardless of any result in a try-catch.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your birth year: ");
try{
int birthyear = sc.nextInt();
int age = 2022 - birthyear;
System.out.println("Your age is "+age);
}catch (Exception ex){
System.out.println("Error make sure input is correct.");
}finally{
System.out.println("This is finally. ");
}
}
}