[go: up one dir, main page]

0% found this document useful (0 votes)
2 views2 pages

Try, Catch, Finally

The document is a Java program demonstrating exception handling for various scenarios. It includes handling for InputMismatchException, ArithmeticException, and ArrayIndexOutOfBoundsException, providing user prompts and error messages for invalid inputs. The program ensures input processes are completed and resources are cleaned up using finally blocks.

Uploaded by

jemuel lago
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Try, Catch, Finally

The document is a Java program demonstrating exception handling for various scenarios. It includes handling for InputMismatchException, ArithmeticException, and ArrayIndexOutOfBoundsException, providing user prompts and error messages for invalid inputs. The program ensures input processes are completed and resources are cleaned up using finally blocks.

Uploaded by

jemuel lago
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

package ricks;

import java.util.InputMismatchException;
import java.util.Scanner;

public class ExceptionHandlingDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Handling InputMismatchException
try {
System.out.print("Enter an integer: ");
int number = scanner.nextInt(); // Expects an integer
System.out.println("You entered: " + number);
} catch (InputMismatchException e) {
System.out.println("Caught InputMismatchException: Please enter a valid integer.");
} finally {
scanner.nextLine(); // Clear the buffer
System.out.println("Input process completed.");
}

// Handling ArithmeticException
try {
System.out.print("Enter a divisor: ");
int divisor = scanner.nextInt();
int result = 10 / divisor; // Division operation
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: Division by zero is not allowed.");
} finally {
System.out.println("Arithmetic operation attempted.");
}

// Handling ArrayIndexOutOfBoundsException
try {
int[] arr = {1, 2, 3};
System.out.print("Enter an array index (0-2): ");
int index = scanner.nextInt();
System.out.println("Array value at index " + index + ": " + arr[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: Index out of range.");
} finally {
System.out.println("Array access attempted.");
}

scanner.close();
}
}
Invalid inputs result

Divisor

Array

You might also like