

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
This java program demonstrates exception handling during division operation. The user is prompted to input two numbers, which are then converted to integers and divided. The program catches arithmeticexception and numberformatexception, displaying error messages and prompting the user to try again. The finally block is used to print motivational messages.
Typology: Assignments
1 / 2
This page cannot be seen from the preview
Don't miss anything!
// import the package to accept the input import java.io.*; public class ExceptionExercise { public static void main(String[] args) throws Exception { // create object for the input BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); // create and declare the local variables String first; String second; int dividend; int divisor; int answer; try { //Ask the user for the first number System.out.print("Enter the first number: "); first = dataIn.readLine(); //Ask the user for the second number System.out.print("Enter the second number: "); second = dataIn.readLine(); //convert the input to numbers dividend = Integer.parseInt(first); divisor = Integer.parseInt(second); //perform division answer = (dividend/divisor); //display the result System.out.println("The answer is " + answer + "."); } catch(ArithmeticException ex) { System.out.println("Error! " + ex.getMessage() + "."); System.out.println("Try Again."); } catch(NumberFormatException ex) { System.out.println("Error! " + ex.getMessage() + "."); System.out.println("Try Again."); } finally { System.out.println("Programming is fun."); System.out.println("I am starting to love it."); } } }