Problem Solving with C++ plus MyProgrammingLab with Pearson eText-- Access Card Package (9th Edition)
9th Edition
ISBN: 9780133862218
Author: Walter Savitch
Publisher: PEARSON
expand_more
expand_more
format_list_bulleted
Question
Chapter 16.1, Problem 3STE
Program Plan Intro
Exception:
An exception is a problem that creates during the execution of a program; it offers a method to transfer control from one part to another part of a program.
An exception handling is created by using the following three keywords such as try, catch and throw.
- The “try” block have the program for the basic
algorithm that says the computer what to do when all goes well. - The “throw” keyword throws an error statement to the “catch” block.
- The “catch” block will catch the exception or handling the exception.
Generally, the compiler executes “try” block. In the “try” block, if the statements cause an exception, it throws an error statement to the “catch” block using the keyword “throw”. The “catch” block then handles the error based upon the type of exception.
Expert Solution & Answer
Want to see the full answer?
Check out a sample textbook solutionStudents have asked these similar questions
What is the difference between using @Test(expected = TypeOfException) and using try/catch when testing if a method or constructor properly returns an exception?
A. They do the same thing.
B. @Test(expected = ...) is the proper way to unit test in java, and try/catch should only be used when unit testing in Python.
C. @Test(expected = ...) will give a passing test as soon as one exception of the proper type is thrown and then stop the test, but using try/catch will allow you to test many examples in the same test and will only stop after running all examples or reaching a fail() or an assert statement that fails.
D. We should never use try/catch when unit testing, otherwise we will catch the exception and then won't know if it is actually thrown.
Complete both Unit Tests using the given code
Unit Test #1
performOperation addition test
Build Output
NtTest6b116967.java:9: error: performOperation(double,double,String) has private access in Calculator assertTrue(tester201.performOperation(5, 2, "+") == 7.00);
^
Test Contents
Calculator tester201 = new Calculator();
@Test
public void unitTest() {
assertTrue(tester201.performOperation(5, 2, "+") == 7.00); }
Unit Test #2
performOperation multiplication test
Build Output
NtTeste16b3fd1.java:9: error: performOperation(double,double,String) has private access in Calculator assertTrue(tester202.performOperation(5, 2, "*") == 10);
Test Contents ^
Calculator tester202 = new Calculator();
@Test public void unitTest() {
assertTrue(tester202.performOperation(5, 2, "*") == 10); }
The Given Code
// Calculator.java - This program performs arithmetic, ( +. -, *. /, % ) on two…
4.) How many times is the println statement executed? for (int i = 0; i < 10; i++) for (int j = 0; j <= 5; j++) System.out.println(i * j) a. 100 b. 60 c. 50 d. 45 5.) Will the following program terminate? int balance = 10; while (true) { if (balance < 9) break; balance = balance - 9; } a.Yes
b. No
6.) What exception type does the following program throw? public class Test { public static void main(String[] args) { System.out.println(1 / 0); } } a. ArithmeticException b. ArrayIndexOutOfBoundsException c. StringIndexOutOfBoundsException d. ClassCastException e. No exception
Chapter 16 Solutions
Problem Solving with C++ plus MyProgrammingLab with Pearson eText-- Access Card Package (9th Edition)
Ch. 16.1 - Prob. 1STECh. 16.1 - What would be the output produced by the code in...Ch. 16.1 - Prob. 3STECh. 16.1 - What happens when a throw statement is executed?...Ch. 16.1 - In the code given in Self-Test Exercise 1, what is...Ch. 16.1 - Prob. 6STECh. 16.1 - Prob. 7STECh. 16.1 - What is the output produced by the following...Ch. 16.1 - What is the output produced by the program in...Ch. 16.2 - Prob. 10STE
Knowledge Booster
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.Similar questions
- C++Write a program SEGMENT that does the following: Asks the user for his/her birthday using 2 integer values, i.e., int month, int year. Using a try/catch block with two catch blocks, check for the following exceptions: Invalid month (i.e., a month less than or equal to 0 or greater than 12). Throw a string exception to be caught by a catch block accepting a string. Output the message thrown by the exception indicating the month is an invalid month. Year less than 1900 or greater than 2020. Throw an integer exception to be caught by a catch block accepting an integer. In the catch block, if the integer thrown is less than 1900, output the message “You are very old”. If the integer exception is greater than 2020, output the message “You have not been born yet!” If neither exception occurs, simply output (cout) a message with the user’s birth month and year, for example, “You were born in “ << month << “ and “ << year. Declare any variables needed.…arrow_forwardConsider the following test method code fragment, which tests whether a method given invalid input produces the expected exception in response. On which of the following lines should the test return false, indicating that the test has failed? There may be more than one correct answer! try { methodCall(invalidInput); // 1. line after method call } catch (IllegalArgumentException e) { // 2. correct } catch (Exception e) { // 3. incorrect } Group of answer choices 1. line after method call 2. correct 3. incorrectarrow_forwardCreate a Junit Parameterized Test for Testing Factorials from n= 0 to 30? Take snapshots of .java, Test.java files and output of test cases. Also upload codearrow_forward
- The following code is causing an exception during the runtime. class test{ public static void main(String[] args) { Object o = "Hello"; Object s = new Random(); m(o); m(s); } public static void m(Object o) { String s = (String)o; System.out.println(s.length()); }} Exception can be prevented by adding an if statement and type casting in the method m Exception can be handled by adding try-catch in the main method answers A or B both works Non of the answersarrow_forwardin java Write a program that reads integers userNum and divNum as input, and output the quotient (userNum divided by divNum). Use a try block to perform the statements. Use a catch block to catch any ArithmeticException and output an exception message with the getMessage() method. Use another catch block to catch any InputMismatchException and output an exception message with the toString() method. Note: ArithmeticException is thrown when a division by zero happens. InputMismatchException is thrown when a user enters a value of different data type than what is defined in the program. Do not include code to throw any exception in the program. Ex: If the input of the program is: 15 3 the output of the program is: 5 Ex: If the input of the program is: 10 0 the output of the program is: Arithmetic Exception: / by zero Ex: If the input of the program is: 15.5 5 the output of the program is: Input Mismatch Exception: java.util.InputMismatchException LabProgram.java…arrow_forwardSuppose you are asked to test the code below. The code: public String allocateRoom(int numOfEmps) throws IllegalArgumentException { if (numOfEmps == 0) throw new IllegalArgumentException(); if (numOfEmps < 5) return "Small"; if (numOfEmps < 10) return "Standard"; return "Large"; } Throws exception if there are no employees Returns small up to 5 employees Returns standard for 5 to 9 employees Returns large for 10 or more employees List the minimum amount of test inputs that achieve 100% branch coverage. You need to specify the branch(es) each input covers. List the minimum amount of test inputs that achieve 100% path coverage. You need to specify the path each input covers. Explain if executing the test suites above will reveal any defects.arrow_forward
- Assume you are considering writing a method and are deciding what should happen when given input that is outside of perfect input. Which of the following is not a way to handle this? Group of answer choices 1. Use better JUnit testing 2. Throw an exception 3. Try to reasonably auto-correct 4. Prevent the errorarrow_forwardProgramme Leader of ITMB wants to check whether the student number and GSM number entered by the student for the programming contest is valid or not. Write a Java program to read the Student ID and GSM Number of a student. Use a method called ValidityDetails () for checking the validity of details entered. If the Student ID doesn’t start with the characters ST and contains more than 6 letters or if the Mobile Number does not contain exactly 8 digits, throw a user defined exception InvalidDetailsException. If the details entered are valid, display the message ‘”correct details are entered!!!” otherwise display “Entered invalid details!!!!”arrow_forwardSolve In Python Provide Screenshots of Input and Ouput For this lab, you will modify your Lab 7 to make several improvements to the getter/settermethods. Instead of having them return True/False, modify each one to throw an exception ifinvalid data is passed.Modify these methods in the following way:• add_hours()o If the number of hours being added is less than 0, throw an exception• add_sales()o If the amount of sales being added is less than 0, throw an exception• set_employee_number()o The employee number must be an integer. If the given input is not an integer,throw an exception• set_office_number()o If the office number given is less than 100 or greater than 500, throw anexception.• set_name()o If the given name is empty, throw an exceptiono Any of the following characters should be removed from the name: ‘_’, ‘.’, ‘-‘ (Underscore, period, and dash)• set_birthdate()o If the given value for the month is less than 1 or greater than 12, throw anexceptiono If the given value for the…arrow_forward
- Write a program that reads integers user_num and div_num as input, and output the quotient (user_num divided by div_num). Use a try block to perform all the statements. Use an except block to catch any ZeroDivisionError and output an exception message. Use another except block to catch any ValueError caused by invalid input and output an exception message. Note: ZeroDivisionError is thrown when a division by zero happens. ValueError is thrown when a user enters a value of different data type than what is defined in the program. Do not include code to throw any exception in the program. Ex: If the input of the program is: 15 3 the output of the program is: 5 Ex: If the input of the program is: 10 0 the output of the program is: Zero Division Exception: integer division or modulo by zero Ex: If the input of the program is: 15.5 5 the output of the program is: Input Exception: invalid literal for int() with base 10: '15.5' My code: # Type your code here.user_num = input()div_num =…arrow_forwardWrite a program that reads integers user_num and div_num as input, and output the quotient (user_num divided by div_num). Use a try block to perform all the statements. Use an except block to catch any ZeroDivisionError and output an exception message. Use another except block to catch any ValueError caused by invalid input and output an exception message. Note: ZeroDivisionError is thrown when a division by zero happens. ValueError is thrown when a user enters a value of different data type than what is defined in the program. Do not include code to throw any exception in the program. Ex: If the input of the program is: 15 3 the output of the program is: 5 Ex: If the input of the program is: 10 0 the output of the program is: Zero Division Exception: integer division or modulo by zero Ex: If the input of the program is: 15.5 5 the output of the program is: Input Exception: invalid literal for int() with base 10: '15.5' My code: # Type your code here.user_num = int(input())div_num =…arrow_forwardWhat output is produced by the following code?int waitTime = 46;try{cout << "Try block entered.\n";if (waitTime > 30)throw waitTime;cout << "Leaving try block.\n";}catch(int thrownValue){cout << "Exception thrown with\n"<< "waitTime equal to " << thrownValue << endl;}cout << "After catch block" << endl;arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- Microsoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,
Microsoft Visual C#
Computer Science
ISBN:9781337102100
Author:Joyce, Farrell.
Publisher:Cengage Learning,
.2: Function Parameters and Arguments - p5.js Tutorial; Author: The Coding Train;https://www.youtube.com/watch?v=zkc417YapfE;License: Standard Youtube License