Rectangle Class Include Try-catch And Exception Handling
Oct 18, 2014
The requirement is to write a rectangle class and a test class, which include try-catch blocks and exception handling. Exceptions, involving try, catch, throw, throws, and finally commands,how to write a code about basic things, but in the test class, it gives me specific width and height so that i dont konw how to write a try-catch blocks an exception handling in this test class.There is my two classes, they are separated.
public class Rectangle {
double width ;
double height ;
Rectangle(){
width = 1;
height = 1;
I have studied about the hierarchy of exception classes in which Throwable class comes at the top and two of its direct subclasses are Error and Exception..I just want to ask if in some code snippet we throw an instance of Error or its subclass within the try catch block then will that be also called "exception handling" ? I am asking this because Error class is not a child class of Exception therefore cant be said an Exception, therefore handling the same should not be called exception handling
I was giving a quick skim to some tutorials on the internet where I have found the exception that is handled is also declared in the throws clause of the method wrapping the try-catch block. For a code representation consider the following:
public void methodName() throws IOException { try { ... } catch (IOException ex) { .... TODO handle exception }
I came across a code where the exceptions can be thrown from catch and finally block too. I never gave a thought on what scenarios that can be required. Some practical examples when/where it can be required to throw the exception from catch and finally blocks.
Is there any connection between packages and exception handling in java. Means is it necessary to create a package before trying exception handling examples?
Is there a special mechanism through which exception can be handled in a constructor?
Suppose while creation of an object there occurred an exception while creating an object, and the object is half constructed. How do we make sure we handle this kind of exceptions in a constructor?
For one of my last labs for the semester, my professor is having the class go back to our very first program and apply some of the exception handling that we just recently learned about. Here's my improved code so far:
Java Code: import java.util.*; import java.lang.*; public class Lab2Part1 { public static void main (String [] args) { Scanner input = new Scanner (System.in);
[code]....
My code compiles fine, but even if I enter an integer or a double, it saves the number as a string, and prints that out as the name. Is there any way to get around this? Or do I need to use something besides a try-catch?
I have been working on a problem dealing with exception handling and text input output for a few days now. The exercise is a two part exercise. The first part of the exercise I have to write a program to display the total salary for assistant professors, associate professors, full professors, and all faculty, respectively, and display the average salary for assistant professors, associate professors, full professors, and all faculty, respectfully using the what is posted on the [URL] .... Each line in the file consists of a faculty member's first name, last name, rank, and salary. The second part of the exercise I have to take my code and change it so that it
-lets the user enter the name of the file to be read, -Uses a try-catch block to handle the FileNotFoundException displaying instead The file already exists.. ... Use a second catch block to ignore any other exception thrown. ... Design your code so that, if the user enters a file that does not exist, the program prompts the user to enter again a file name.
and I need to Note: In order to catch the FileNotFoundException, you need to include import
I want to write classes with methods that perform JDBC operations that throw SQL exceptions. For many of the methods, I'd ideally like to be able to have them catch exceptions and just send them to a standard Logging system "IF" the code that calls the methods is not going to catch the same exception. However, I'd like the "option" to have code that calls these methods catch the same errors if I want to but not "Require" the calling routines to catch them.... so I don't want to declare the methods with a "throws" that would require all calling code to Try/catch.
For some background, the logic behind what I'm looking to do is that there will be lots of places where these classes and their methods may be used where the code is basically "throw away" scripting code where just having error logs generated is more than sufficient. However there are also places I want to use the same classes/methods that I would want to handle the exception differently. So, for at least half the places I want to use these methods, there's no good reason to require cluttering the calling code with Try/catch, but when I DO want to handle the exceptions, I'd like them to get passed up to the calling routine so I can handle them in a way that is appropriate for the calling routine. Does that make sense?
I guess I'm kind of looking for is the ability to "override" the catch of a called method "IF" I want to but to treat the method as though it doesn't throw any exception "IF" I don't want to override the called routines catch logic.
If I put the highlighted text in try/catch block it is throwing NullPointerException , if I am using command line arguments then also it is showing the same exception.
java 7 feature (Multicatch and final rethrow ).. how to print user defined message in catch block with respect to multiple exceptions in single catch block...
Ex: }catch (IOException | SQLException ex) { System.out.println("Exception thrown"); /** * i want like this, if IOException is thrown then System.out.println("File not Found"); * if SQLException is thrown then System.out.println("DataBase Error"); */ }
what is the use of checked exception.I know unchecked exception or Runtime exception are thrown by jvm whenever programmer makes any mistake in logic and current thread is terminated.But checked Exception are checked at compile time so that compiler compels programmer to put risky methods in try catch clause. And this checked Exception are caused due to problem in IO operation or any such operation which the programmer can't control.Programmer can't do anything to avoid this checked exception but can catch this exception.
Now the question is Why compiler compels checked exception to be put in try catch clause but doesn't complain anything in case of Runtime Exception???
I know I can calculate the sum of squares as such:
// SumSquares.java: calculate the sum of two squares class SumSquares { static int sumSquares(int a, int B)/>/> { int asquare; int bsquare;
[Code] ....
But how can I modify the code so that it inputs a list of integer values in the range of -100 to 100 from the keyboard and computes the sum of the squares input values. And how would I go about using exception handling to ensure that the input values are in range and are legal integers.
I am trying to learn how to use file input/output in addition to exception handling... The problem is my textbook wrote this chapter for a version of Java that hasn't come out yet, so everything I do "according to the textbook" doesn't work. any feedback on correcting these exception errors because I am not sure what is causing them or how to fix them.
I was able to have it display the name of the book in the Book.txt file, but when I added the second part if the file doesn't exist, that's when the errors came up and it wouldn't compile.
import java.io.*; import java.util.*; public class DisplayBook { public static void main(String[] args) { try { File book = new File("Book.txt"); FileInputStream in = new FileInputStream(book);
[Code]...
These are the compilation error messages I am receiving: (I have managed to get it down from 7 errors to just 4, but now I'm stuck)
DisplayBook.java:15: error: unreported exception IOException; must be caught or declared to be thrown while ((letter = in.read()) != -1) //if file exists, displays book title ^ DisplayBook.java:24: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
class MultipleReturn { int getInt() { int returnVal = 10; try { String[] students = {"Harry", "Paul"}; //System.out.println(students[5]); //if i remove comment
I know I can calculate the sum of squares as such:
// SumSquares.java: calculate the sum of two squares class SumSquares { static int sumSquares(int a, int B)/>/> { int asquare; int bsquare;
[Code] .....
But how can I modify the code so that it inputs a list of integer values in the range of -100 to 100 from the keyboard and computes the sum of the squares input values. And how would I go about using exception handling to ensure that the input values are in range and are legal integers.
I have written the following code to calculate tax payments based on income and filing status :
import java.util.Scanner; public class computeTax { public static void main(String[] args) { Scanner input = new Scanner(System.in); // prompt for filing status System.out.println("enter '0' for single filer,");
[Code] ....
The while loop initiated on line 21 is there so that in case the wrong input is given at the prompt given in line 24, the program outputs "please type the right answer" with the command on line 254 before looping back to line 24 and prompting the user to enter his status number. The program works as long as the input at line 28 is an integer. Not surprisingly if the erroneous input here is not an integer, the program outputs the following error message :
Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909) at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextInt(Scanner.java:2160) at java.util.Scanner.nextInt(Scanner.java:2119) at computeTax.main(computeTax.java:28
To try to solve this I used the Try / Catch technique with the following version of the code :
import java.util.Scanner; public class computeTax { public static void main(String[] args) { Scanner input = new Scanner(System.in); // prompt for filing status System.out.println("enter '0' for single filer,");
Modify class Time2 to include a tick method that increments the time stored in a Time2 object by one second. Provide method incrementMinute to increment the minute and method incrementHour to increment the hour. The Time2 object should always remain
a) incrementing into the next minute,
b) incrementing into the next hour and
c) incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).
how to manage case 4 stuff and what's the problem of this CODE.
import java.util.Scanner; public class Time2Test { public static void main( String args[] ) { Scanner input = new Scanner( System.in ); Time2 time = new Time2(); // input System.out.println( "Enter the time" ); System.out.print( "Hours: " ); time.setHour( input.nextInt() );
There is a method taken from a class with several try and catch blocks. If you think it is possible, add one more catch block to the code to catch all possible exceptions, otherwise say 'Not possible' with your reason.
I was told to design a class named Rectangle to represent a rectangle.The class contains:
■ Two double data fields named width and height that specify the width and height of the rectangle. The default values are 1 for both width and height. ■ A no-arg constructor that creates a default rectangle. ■ A constructor that creates a rectangle with the specified width and height. ■ A method named getArea() that returns the area of this rectangle. ■ A method named getPerimeter() that returns the perimeter.
Draw the UML diagram for the class and then implement the class. Write a test program that creates two Rectangle objects one with width 4 and height 40 and the other with width 3.5 and height 35.9. Display the width, height, area,and perimeter of each rectangle in this order.Here is my code for the Rectangle Class:
class Rectangle { double width; double height; public Rectangle() { width = 1; height = 1;
[code]....
The error that I am given when I compile the driver is as follows:constructor Rectangle in class Rectangle cannot be applied to given types; required: no arguments; found:int,int; reason: actual and formal argument lists differ in length.
Write an instance method, contains, that has one explicit parameter of type Rectangle. The method should return true if every point of the rectangle determined by the explicit parameter is on or within the rectangle determined by the implicit parameter. It should return false otherwise.
Right, so I got this program. It takes input from the user and assigns it to fields on an object. But, it's meant to check the users input. If the user enters bad input, it's supposed to throw this exception. For each of these exceptions, theres a class specifically for it.
public class PayrollDemo { public static void main(String[] args) { Payroll pr = new Payroll ("Test Name", 234); System.out.println("Current Employee Information. "); System.out.println("Name: " + pr.getName()); System.out.println("ID: " + pr.getID()); System.out.println("Hourly Pay Rate: " + pr.getHourlyPayRate());
[Code] ....
And this is the exception class.
public class InvalidNameException extends Exception { /** No-arg constructor */ public InvalidNameException() { super("Invalid name"); } }
PayrollDemo.java:43: error: cannot find symbol InvalidNameException.InvalidNameException(); ^ symbol: method InvalidNameException() location: class InvalidNameException 1 error
It's just meant to tell the user that they entered an invalid value, which would mean if they entered an empty string instead of a name.