Consider the program can potentially make mathematical run-time errors. Scenario
ID: 3854898 • Letter: C
Question
Consider the program can potentially make mathematical run-time errors. Scenarios considered run-time errors include division and multiplication by zero, addition leading to a number greater than 255 and subtraction leading to a number less than 0
Define exception class with a private data member of type string that stores an error message that you’ll use in your catch block. The class also requires a parametrized constructor and an accessor function.
In main function ask the user to perform an operation (division, multiplication, addition, and subtraction), and for 2 integers to perform the operation
For each operation, check if an exception occurred and throw an object of your exception class to create a suitable message indicating what error has occurred. If no errors, calculate the appropriate result and display it. if-else or switch-case function may be used to branch between operation. Only one catch block may be used in code, which is designed to catch all 4 case errors. Let the user know which error occurred if one occurs.
Explanation / Answer
import java.util.*;
public class ExceptionClass
{
private String errorMessage="";
public static void main(String[]args)
{
Scanner scan=new Scanner(System.in);
System.out.println("YOU HAVE FOLLOWING CHOICES : ");
System.out.println("1. Addition");
System.out.println("2. Subtraction ");
System.out.println("3. Multiplication ");
System.out.println("4. Divison");
System.out.println("Enter your choice : ");
int choice=scan.nextInt();
//Taking or accepting inputs from the user(keyboard)
System.out.println("Enter First Number: ");
int a=scan.nextInt();
System.out.println("Enter Second Number ");
int b=scan.nextInt();
double result=0;//'result' will store the result of operation
try
{
switch(choice) //switch case used to branch between operation
{
case 1:
result=a+b;
if(result>255){System.out.println("Error");}//checks the result
System.out.println(result);
break;
case 2:
result=a-b;
if(result<0){System.out.println("Error");}
System.out.println(result);
break;
case 3:
if(a==0 || b==0){System.out.println("Error");} //Checks whether a or b is zero or not
else
{
result=a*b;
System.out.println(result);
break;
}
case 4:
result=a/b;
System.out.println(result);
default:
System.out.println("Wrong Choice");
}
}
catch(Exception e) //Catch block to catch the and throw which exception has occured
{
System.out.println(e);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.