Concept explainers
a.
Finally block:
Finally block contains block of code and the block is executed after a try-catch block.
- If there is no errors in try block, finally statement is executed after try block executed.
- If there is error in try block, then catch block caught the exception, rest of try block is skipped, and then executes the finally statement.
- If there is error in try block, then catch block does not caught that exception, rest of try block is skipped, executes only finally statement, and then skip the rest of the code.
- Thus, finally block handle such case and it contains block of statement. Once try-catch block gets executed, finally block is executed.
General form for finally block:
// class definition
class class_name
{
//...
// Try block
try
{
// Try block statement
}
// Catch block
catch(Excep1 exObj)
{
// Catch block statement
}
// Catch block
catch(Excep2 exObj)
{
// Catch block statement
}
//...
//Finally block
finally
{
//finally block statement
}
//...
}
Given code:
//Try block
try
{
statement1;
statement2;
statement3;
}
//Catch block
catch (Exception1 ex1)
{
}
//Finally block
finally
{
statement4;
}
statement5;
b.
Finally block:
Finally block contains block of code and the block is executed after a try-catch block.
- If there is no errors in try block, finally statement is executed after try block executed.
- If there is error in try block, then catch block caught the exception, rest of try block is skipped, and then executes the finally statement.
- If there is error in try block, then catch block does not caught that exception, rest of try block is skipped, executes only finally statement, and then skip the rest of the code.
- Thus, finally block handle such case and it contains block of statement. Once try-catch block gets executed, finally block is executed.
General form for finally block:
// class definition
class class_name
{
//...
// Try block
try
{
// Try block statement
}
// Catch block
catch(Excep1 exObj)
{
// Catch block statement
}
// Catch block
catch(Excep2 exObj)
{
// Catch block statement
}
//...
//Finally block
finally
{
//finally block statement
}
//...
}
Given code:
//Try block
try
{
statement1;
statement2;
statement3;
}
//Catch block
catch (Exception1 ex1)
{
}
//Finally block
finally
{
statement4;
}
statement5;
c.
Finally block:
Finally block contains block of code and the block is executed after a try-catch block.
- If there is no errors in try block, finally statement is executed after try block executed.
- If there is error in try block, then catch block caught the exception, rest of try block is skipped, and then executes the finally statement.
- If there is error in try block, then catch block does not caught that exception, rest of try block is skipped, executes only finally statement, and then skip the rest of the code.
- Thus, finally block handle such case and it contains block of statement. Once try-catch block gets executed, finally block is executed.
General form for finally block:
// class definition
class class_name
{
//...
// Try block
try
{
// Try block statement
}
// Catch block
catch(Excep1 exObj)
{
// Catch block statement
}
// Catch block
catch(Excep2 exObj)
{
// Catch block statement
}
//...
//Finally block
finally
{
//finally block statement
}
//...
}
Given code:
//Try block
try
{
statement1;
statement2;
statement3;
}
//Catch block
catch (Exception1 ex1)
{
}
//Finally block
finally
{
statement4;
}
statement5;
Want to see the full answer?
Check out a sample textbook solutionChapter 12 Solutions
Introduction to Java Programming and Data Structures, Comprehensive Version, Student Value Edition (11th Edition)
- How can the default error message be shown whenever an exception is thrown?arrow_forwardUsing Java Define a Rubric class that extends the GradedActivity class shown below. The Rubric class should determine the grade a student receives for a chapter lab. Using the following points: Algorithm: 20 points Variables: 5 points Formulas: 5 points Test Data: 15 points UML: 20 points Code: 35 points Create exception classes for 2 error conditions. You determine which errors for the exceptions. Demonstrate the class in a simple program. GradedActivity public class GradedActivity { private double score; // holds the score public void setScore (double s) { score=s; } //end method for setting the score public double getScore() { return score; }// end method to return the score public char getGrade() { // return a letter grade determined by the scores listed below char letterGrade; if (score >= 90) letterGrade = 'A'; else if (score >=80) letterGrade = 'B'; else if (score >=70)…arrow_forwardInstructions: Exception handing Add exception handling to this game (try, catch, throw). You are expected to use the standard exception classes to try functions, throw objects, and catch those objects when problems occur. At a minimum, you should have your code throw an invalid_argument object when data from the user is wrong. File GamePurse.h: class GamePurse { // data int purseAmount; public: // public functions GamePurse(int); void Win(int); void Loose(int); int GetAmount(); }; File GamePurse.cpp: #include "GamePurse.h" // constructor initilaizes the purseAmount variable GamePurse::GamePurse(int amount){ purseAmount = amount; } // function definations // add a winning amount to the purseAmount void GamePurse:: Win(int amount){ purseAmount+= amount; } // deduct an amount from the purseAmount. void GamePurse:: Loose(int amount){ purseAmount-= amount; } // return the value of purseAmount. int GamePurse::GetAmount(){ return purseAmount; } File…arrow_forward
- When will be the else part of try-except-else be executed? a. None of these b. when no exception occurs c. always d. when an exception occursarrow_forwardProblem Statement:The purpose of this lab assignment is to gain experience in python’s Exception handling. In thisassignment, you will write a program for .edu email address validation system. Problem Design: The program will take an email address from user and check if it contains thefollowing:a. Address must contain at least an ‘@’ symbolb. Address must contain at least a ‘.edu’ suffixc. Length must contain at least 12 characters.d. Address must contain at least one digit 2. Helper functions to check if an address has at least one digit is provided. Docstring arealso given in the template file. This function returns True if condition satisfies otherwisereturns False. 3. Your task: Design a base class (Invalid Address) and child exception classes(InsufficientLength, NoDigit, NoEdu, NoAtSymbol ) to raise the exception when theconditions are not met. 4. Design a simple user menu to ask for the address as long as the user does not enter a validaddress. 5. The menu should also make a…arrow_forward"Determine which exception is needed for each case and put them in the corresponding catch statement with the appropriate variable. Do NOT use the general exception handler Exception for any one. Possible Exceptions: IOException, ArithmeticException, StringIndexOutOfBoundsException, NullPointerException, ArrayIndexOutOfBoundsException" public String catchErrors(int choice) {switch (choice) {case 1:try {String word;word = null;word.charAt(0);} catch () { //TODOreturn e.toString();}break;case 2:try {int[] array = new int[5];array[5] = 11;} catch () { //TODOreturn e.toString();}break;case 3:try {int ans = 7 / 0;} catch () { //TODOreturn e.toString();}break;}return null;}arrow_forward
- 1 Please provide a basic exception code. Do not use input, output. Please provide code and explain. Thank you. Write the Java code for the following: Write the InvalidGradeException class that will be used below. Write the Java program that reads an integer grade from a user and checks that it is valid (between 0 and 100). If it is invalid an InvalidGradeException will be thrown, stating what the invalid grade is. This will be caught in the main( ) method which will write a message about the invalid grade. If the grade is valid, it is written to the monitor..arrow_forward1. What type of exception does the following code raise? print(3+"test") 2. What type of exception does the following code raise? print(3"test")arrow_forwardException handling The reciprocal of a number is 1 divided by that number. The starter program below is expected to compute the reciprocal of all the numbers in a list. Fix the starter program to safely catch and handle incorrect divisions accordingly. If an exception occurs, catch the exception and print the exception. Your output should match the expected output below. Expected output The reciprocal of 1 is 1.0 The reciprocal of 2.5 is 0.4 The reciprocal of -6 is -0.17 division by zero The reciprocal of 0.4 is 2.5 The reciprocal of -0.17 is -5.88 unsupported operand type(s) for /: 'int' and 'str' The reciprocal of 3.14 is 0.32 type complex doesn't define __round__ method The reciprocal of 3.141592653589793 is 0.32 Here is the code from the starter file we are required to use: import math numbers = [1, 5 / 2, -6, 0, 0.4, -0.17, 'pi', 3.14, 2-6j, math.pi] for n in numbers: reciprocal = 1 / n print(f"The reciprocal of {n} is {round(reciprocal, 2)}")arrow_forward
- hello, I am having trouble with my code, I am not able to make it error.arrow_forwardpython Write a program that calculates an adult's fat-burning heart rate, which is 70% of 220 minus the person's age. Complete fat_burning_heart_rate() to calculate the fat burning heart rate. The adult's age must be between the ages of 18 and 75 inclusive. If the age entered is not in this range, raise a ValueError exception in get_age() with the message "Invalid age." Handle the exception in __main__ and print the ValueError message along with "Could not calculate heart rate info." Ex: If the input is: 35 the output is: Fat burning heart rate for a 35 year-old: 129.5 bpm If the input is: 17 the output is: Invalid age. Could not calculate heart rate info. # here is the script I have but its not working def get_age():age = int(input())age=int(input("Enter the age:"))if age<18 or age>75:raise ValueError('Invalid age.')return age # TODO: Complete fat_burning_heart_rate() functiondef fat_burning_heart_rate(age):heart_rate=(220-age)*.70return heart_rate if __name__ == "__main__":#…arrow_forwardc++ programming Lab 10-1: Write a test program to accept two numbers from consol. Then check to see if first number is larger than second number . If it is throwing an exception and handle the error properly. Lab 10-2: Write a test program to accept a number from consol. then check to see if the number is positive or negative. If it is negative throw an exception and indicate the number is negative otherwise take the squire root of the number. Use exception handling to control the flow of the code. Lab 10-3: Write a test program to accept a number from consol. This number is radius of circle if the number is positive find area and circumference. Otherwise, throw an exception with proper message. Lab 10-4: Show the output of the following code with input 10, 60, and 120, respectively.arrow_forward
- Microsoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,C++ for Engineers and ScientistsComputer ScienceISBN:9781133187844Author:Bronson, Gary J.Publisher:Course Technology PtrC++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage Learning
- EBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTProgramming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:Cengage