Introduction
A try-catch block helps your program handle errors without crashing. It lets you try some code and catch problems if they happen.
Jump into concepts and practice - no test required
A try-catch block helps your program handle errors without crashing. It lets you try some code and catch problems if they happen.
try { // code that might cause an error } catch (ExceptionType name) { // code to handle the error }
The try block contains code that might cause an error.
The catch block runs only if an error happens in the try block.
try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero."); }
try { String text = null; System.out.println(text.length()); } catch (NullPointerException e) { System.out.println("Text is null."); }
This program tries to access an array element that does not exist. The catch block handles the error and the program keeps running.
public class TryCatchExample { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; System.out.println(numbers[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Oops! Index is out of range."); } System.out.println("Program continues smoothly."); } }
You can have multiple catch blocks to handle different errors.
Try-catch blocks help keep your program from stopping unexpectedly.
Use try-catch to handle errors safely.
The try block runs code that might fail.
The catch block runs if an error happens, letting you respond nicely.
try-catch block in Java?catch (Exception e).try {
int a = 5 / 0;
System.out.println("Result: " + a);
} catch (ArithmeticException e) {
System.out.println("Error caught");
}ArithmeticException at runtime.ArithmeticException and prints "Error caught".try {
int[] arr = new int[3];
arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index error");
}ArrayIndexOutOfBoundsException, which is correctly caught.import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int num;
try {
num = sc.nextInt();
System.out.println("You entered: " + num);
} catch (Exception e) {
System.out.println("Invalid input");
}sc.nextInt() reads integer input; invalid input throws InputMismatchException, a subclass of Exception.