Today you will learn:
try-catch-finally blocksBy the end, you will be able to handle errors gracefully and validate user input safely.
Use try to wrap code that might throw an exception.
Use catch to handle exceptions.
Use finally to run code regardless of whether an exception occurred.
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num = sc.nextInt();
System.out.println("Number: " + num);
} catch(InputMismatchException e) {
System.out.println("Invalid input!");
} finally {
sc.close();
}
You can handle different types of exceptions separately.
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // may throw ArrayIndexOutOfBoundsException
} catch(InputMismatchException e) {
System.out.println("Invalid input!");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds!");
}
Validate user input to ensure it meets criteria.
Scanner sc = new Scanner(System.in);
int number = -1;
while(number <= 0) {
try {
System.out.print("Enter a positive integer: ");
number = sc.nextInt();
if(number <= 0) {
throw new IllegalArgumentException("Number must be positive!");
}
} catch(InputMismatchException e) {
System.out.println("Invalid input! Enter a number.");
sc.next(); // clear invalid input
} catch(IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
System.out.println("You entered: " + number);
sc.close();
You can define your own exception classes.
class NegativeNumberException extends Exception {
public NegativeNumberException(String message) {
super(message);
}
}
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num = sc.nextInt();
System.out.println("Number: " + num);
} catch(InputMismatchException e) {
System.out.println("Invalid input!");
} finally {
sc.close();
}
Create a program that only accepts positive integers from the user.
Steps:
try-catch to validate inputExample:
import java.util.InputMismatchException;
import java.util.Scanner;
public class PositiveInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number = -1;
while(number <= 0) {
try {
System.out.print("Enter a positive integer: ");
number = sc.nextInt();
if(number <= 0) {
throw new IllegalArgumentException("Number must be positive!");
}
} catch(InputMismatchException e) {
System.out.println("Invalid input! Enter a number.");
sc.next(); // clear invalid input
} catch(IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
System.out.println("You entered: " + number);
sc.close();
}
}