using Java. 13.6 Program: Division By Zero This program will test exception hand
ID: 3571387 • Letter: U
Question
using Java.
13.6 Program: Division By Zero
This program will test exception handling during division.
The user will enter 2 numbers and attempt to divide (in a try block) the 1st number by the 2nd number.
The program will provide for 2 different catch statements:
Division by zero - denominator is zero - program will throw an ArithmeticException object
Division results in a negative number - program will throw an Exception object
The user should be prompted with
For input of 7 and 0 the output should be
For input of 7 and 2 the output should be
For input of 7 and -2 the output should be
L
Lab Submission
13.6.1: Program: Division By Zero
Instructions
Deliverables
DivideByZero.java
We will expect the above file(s) to be submitted
Compile command
javac DivideByZero.java -Xlint:all
We will use this command to compile your code
Submit your files below by dragging and dropping into the area or choosing a file on your hard drive.
DivideByZero.java
Drag files to left, or choose file...
SUBMIT FOR GRADING
Instructions
Deliverables
DivideByZero.java
We will expect the above file(s) to be submitted
Compile command
javac DivideByZero.java -Xlint:all
We will use this command to compile your code
Submit your files below by dragging and dropping into the area or choosing a file on your hard drive.
DivideByZero.java
Drag files to left, or choose file...
SUBMIT FOR GRADING
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.util.Scanner;
public class DivideByZero {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try{
System.out.println("Enter two numbers: ");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
if(num2 == 0)
throw new ArithmeticException("Exception: Division by zero");
double div = (double)num1/(double)num2;
if(div < 0)
throw new Exception("Exception: Division is negative");
System.out.println(num1+"/"+num2+" = "+div);
}catch(ArithmeticException e){
System.out.println(e.getMessage());
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
/*
Sample run:
Enter two numbers:
4
5
4/5 = 0.8
Enter two numbers:
4
0
Exception: Division by zero
Enter two numbers:
9
-4
Exception: Division is negative
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.