How to set up my try and catch block? - java

everyone I am a beginner programmer with a little problem on my hands. I am trying to make test statements for one of my classes for a project and have come across a problem. I can't seem to get my try and catch block to work. I have tried using super and inheritance and everything I can think of, but i can;t get it to work. I also can't tell if I'm testing my class or not. I'm so confused on how to set up a try and catch for this class and help would be nice. Thank you so much in advance. Below is my code:
public Resistor (double resistancevalue, double tolerancevalue, double powerrating)throws Exception {
if (resistancevalue <= 0){
throw new Exception ("The resistance value must be greater than zero.");
}
if (tolerancevalue <=0 || tolerancevalue>=1){
throw new Exception ("The tolerance value must be between zero and one (not incusive).");
}
if (powerrating >=0){
throw new Exception("The power rating must be greater than zero.");
}
else{
this.resistancevalue=resistancevalue;
this.tolerancevalue = tolerancevalue;
this.powerrating = powerrating;
}
}
public double getResistanceValue(){
return resistancevalue;
}
double miniResistance(){
double Minir = resistancevalue*(1.0-tolerancevalue);
return Minir;
}
double maxResistance(){
double Maxr= resistancevalue*(1.0+tolerancevalue);
return Maxr;
}
Test class:
public static void main(String[] args) {
// TODO code application logic here
//Tesing the resistor class
//testing to see if the expection is caught when the resistence value is less than 0
double tolerancevalue = 0.5;
double powerrating = 1;
try {
double resistancevalue=1;
System.out.println("Exception Failed");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

You haven't made any actual call to the Resistor constructor. The following code behaves as expected:
try {
double resistancevalue=1;
// the following line will throw an exception...
Resistor r = new Resistor(resistancevalue, tolerancevalue, powerrating);
System.out.println("Exception Failed");
} catch (Exception e) {
// the exception is caught and printed here
System.out.println(e.getMessage());
}
// prints "The power rating must be greater than zero."

You need to call the Resistor constructor inside of the try-catch statement.
public static void main(String[] args) {
// TODO code application logic here
//Tesing the resistor class
//testing to see if the expection is caught when the resistence value is less than 0
double tolerancevalue = 0.5;
double powerrating = 1;
try {
double resistancevalue=1;
Resistor testResistor = new Resistor(resistancevalue,tolerancevalue, powerrating);
System.out.println("Exception Failed");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

Try and catch work if there is an exception in your program (body of try{here}). if there is not an exception they will not work. That is how they work

Related

How do I Throw an IllegalArgumentException that won't terminate my program?

Ok so I have a method with a switch statement but I left out the rest of the cases because they're not important. In my main method, the operator method is called and passed the parameter "selection" in a while loop until they choose "Q".
When the user enters a negative number, it should throw an exception, print a message, and ignore their input but then loop back to the beginning. When this exception is thrown it terminates the program. Any help would be very much appreciated. Thanks!
public static void operator(String selection) throws IllegalArgumentException{
Scanner input = new Scanner(System.in);
double price;
switch(selection){
case "A":
System.out.println("Enter the price");
if(input.nextDouble()<0){
throw new IllegalArgumentException("Price cannot be a negative value");
}
else{
price = input.nextDouble();
}
break;
case"Q":
System.exit(0);
}
}
An IllegalArgumentException inherits from RuntimeException, for it not to stop your program you can just use a simple try{} catch {} but i don't recommend doing that with Runtime Exceptions. If that's the case, create your own Exception inheriting from java.lang.Exception.
You can use try catch here.
Something like this should work:
public static void operator(String selection) {
Scanner input = new Scanner(System.in);
double price;
switch(selection){
case "A":
System.out.println("Enter the price");
try {
if(input.nextDouble()<0) {
throw new NegativePriceException();
}
} catch (NegativePriceException e) {
System.out.println("The price can't be negative.");
e.printStackTrace();
}
price = input.nextDouble();
break;
case"Q":
System.exit(0);
}
}
And to make your own Exception class you basically need to inherit from Exception (if you want to use try catch on it) or inherit from RuntimeException (if you want it to stop your program from running), like this:
public class NegativePriceException extends Exception {
public NegativePriceException() {
super();
}
}
Java requires that you handle or declare all exceptions. If you are not handling an Exception using a try/catch block then it must be declared in the method's signature.
In your main method you should handle the Exception
public static void main(String args[]) {
//codes
try{
operator("A");
}
catch(IllegalArgumentException e){
e.printStackTrace();
}
}
You've gotten some good answers already on how to handle the exception.
For your case I don't think an exception is appropriate at all. You should get rid of the exception altogether and just handle the problem input by printing an error message and asking for a new input.
Exceptions are for exceptional situations, they should not be part of the normal execution of your code.

Java says I must return an Object, but I'm throwing exceptions

So I'm trying to catch exceptions where I can't return a Directory, but Java won't let me. How do I structure the code so that Java will let me run it?
public Directory pathToDir(String path) throws Exception {
String[] arrayPath = path.split("/");
Directory cwd_copy = FileSystem.getRoot();
try {
// full path
if (path.startsWith("/")) {
for (int x = 1; x < arrayPath.length; x++) {
if (stuff) {
} else {
throw new Exception();
}
}
}
return cwd_copy;
}
catch (Exception e) {
pathErrorMsg();
}
}
No, you may be throwing an exception, but then you catch it and do nothing with it! If you step through that code logically, you'll see that there are possible pathways for the method to end without a Directory being returned and for no exceptions to be thrown. That won't fly.
Consider instead,....
public Directory pathToDir(String path) throws PathToDirException {
String[] arrayPath = path.split("/");
Directory cwd_copy = FileSystem.getRoot();
// full path
if (path.startsWith("/")) {
for (int x = 1; x < arrayPath.length; x++) {
if (stuff) {
} else {
throw new PathToDirException( /* some text goes in here! */ );
}
}
}
return cwd_copy;
}
Where PathToDirException is a checked exception class you've created for problems with this method/class.
Or if you have a try/catch block in the method, and need to then throw an exception, throw your new Exception class, but pass the caught exception into your new exception as a constructor parameter.
If I understand your question, you need a return at the end of your method (in case you catch an Exception instead of returning cwd_copy)
return cwd_copy; // <-- this didn't happen.
} catch (Exception e) {
pathErrorMsg();
// return null; // <-- you could return here.
}
return null; // <-- so you need something. null or cwd_copy
Or add a return in the catch block.
Because an exception could be caught1, a value must still be returned from the catch path.
try {
maybeThrowException();
return X;
}
catch (Exception e) {
// But what is returned here?
}
Either don't catch the exception, [re]throw an exception, or return a value in the case when the catch block is entered.
Since the method is declared to throw an Exception, it probably should throw one on failure - the method contract should specify the result in such a case.
1 Java actually isn't that smart, even if it is a logical way to think about it. The try/catch is treated like an if/else here and all branches must logically lead to a return (or throw). It would still be a compiler error even if the try was empty and could never throw an exception. Consider the following comparison:
if (true) {
return X;
} else {
// But what is returned here?
// (Java does not consider that this can never be reached,
// just as it does not logically consider the content of a `try`.)
}

Eclipse asks for a return statement though I have one

protected int readInt(String prompt) {
try {
System.out.print(prompt);
int i = keyboard.nextInt();
keyboard.nextLine();
return i;
} catch (java.util.InputMismatchException e) {
System.out.println("Error: Insert a number.");
}
}
Hi! Eclipse gives me this error at the method readInt(): "This method must return a result of type int." and gives the example solutions "Add return statement" and "Change return type to void". I've tried to put the return i statement outside the try-and-catch loop, but when I do, the return statement can't find the variable i.
I've been struggeling with this for a while now, and can't seem to make it work... I would appreciate any help! Thank you.
Think about what happens if an InputMismatchException occurs.
Your code will catch it, print "Error: Insert a number.". And then what? Your function is declared to return an int and it has a path in which it does not return anything.
You should either return a value that cannot be returned otherwise, and indicates an error, or rethrow the exception.
In my code i is declared outside of the try-catch block so that the return statement won't have any scope issues. Also it is given the value -1, so if an exception occurs then the function returns -1 to the caller.
protected int readInt(String prompt) {
int i=-1;
System.out.print(prompt);
try {
i = keyboard.nextInt();
keyboard.nextLine();
} catch (java.util.InputMismatchException e) {
System.out.println("Error: Insert a number.");
keyboard.next();
}
return i;
}
After your catch block add a finally block with your return statement:
protected int readInt(String prompt) {
int i = 0;
try {
System.out.print(prompt);
i = keyboard.nextInt();
keyboard.nextLine();
//return i;
} catch (java.util.InputMismatchException e) {
System.out.println("Error: Insert a number.");
} finally{
return i;
}
}
http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
If a method having return type, JVM should expect for a return value after calling this method, In this case return is with only try {}. suppose any case its not executing all statements in try segment then there is no return type , thats why you got compiler error. You can either put return inside catch segment and try segment or outside of both try and catch
Since you are consuming InputMismatchException, it will not know what to return in case the InputMismatchException is thrown. You can either throw some Exception or have some return in the catch block.

Java - Catching multiple exceptions and Identifying which exception occured

I had some difficulty with the title, wasn't sure how to word it more accurately.
I'm having this issue, I have a several methods which ask the user for 3 Double inputs.
For each input it checks if it's valid (for example if its a positive value), if it's not it throws an IllegalArgumentException. Now I made a Tester class to check if the methods are working properly. It's supposed to catch the exception thrown by the methods and re-ask the user for the input which caused that specific exception.
All 3 methods throw and IllegalArgumentException but the error message is different for each one. Is there anyway (when catching the exception) to see which input cause the error? Here's a sample of my code:
public class account
{
double value;
public account(double initialValue)
{
if (initialValue < 0)
{
throw new IllegalArgumentException("Initial value cannot be negative.");
}
value = initialValue;
}
public add(double addValue)
{
if (addValue < 0)
{
throw new IllegalArgumentException("Added value cannot be negative.");
}
value = value + addValue;
}
}
and the tester class would be something like:
public class accountTester
{
public static void main(String[] args)
{
try
{
double initialValue = Double.parseDouble(JOptionPane.showInputDialog("Enter initial value"));
account acc = new account(initialValue);
double addValue = Double.parseDouble(JOptionPane.showInputDialog("Enter value to add"));
acc.add(addValue);
} catch (Exception e) {
System.out.println("Wrong ammount");
initialValue = Double.parseDouble(JOptionPane.showInputDialog("Re-enter ammount"));
}
}
So what would I have to change in the tester class to throw that code only if the IllegalArgumentException is "Initial value cannot be negative."
Sorry if I made this hard to understand.
EDIT: According to my prof, we're supposed to use do
String error = e.toString;
if (error.contains("Added value cannot be negative.")
{
//DO CODE FOR FIRST ERROR
}
I know this isn't the most proper way of doing it though.
Since you can't match over Strings like you would do in a functional language you have to provide three different kind of objects if you want to be able to distinguish them using the try-catch mechanics.
Or with a simplified approach attach a parameter to the exception so that you can use just a catch clause but you could behave differently. Something like
class MyIllegalArgumentException extends IllegalArgumentException {
public int whichParameter;
public MyIllegalArgumentException(String string, int which) {
super(string);
whichParameter = which;
}
}
now you can:
catch (MyIllegalArgumentException e) {
if (e.whichParameter == 0)
..
else if (e.whichParameter == 1)
..
}
You could also check the string for equality but this would be really not a good design choice, you could also have many try-catch blocks but this is not always possible.
After having expanded your code the solution is easy:
public static void main(String[] args) {
try {
double initialValue = ...
account acc = new account(initialValue);
} catch (IllegalArgumentException e) {
...
}
try {
double addValue = ...
acc.add(addValue);
} catch (Exception e) {
System.out.println("Wrong ammount");
initialValue = Double.parseDouble(JOptionPane.showInputDialog("Re-enter ammount"));
}
}
Surround each method call with its own try/catch block?
In your catch block you should only catch IllegalArgumentException. Then what you can do is invoke the getMessage() function which will enable you to do a very simple String.equals call.

In Java, what is the best way of continuing to call a function until no exception is thrown?

In my Java code, I have a function called getAngle() which sometimes throws a NoAngleException. Is the following code the best way of writing a function that keeps calling getAngle() until no exception is thrown?
public int getAngleBlocking()
{
while(true)
{
int angle;
try
{
angle = getAngle();
return angle;
}
catch(NoAngleException e)
{
}
}
}
Or would it be a better idea to rewrite getAngle() to return NaN upon error?
I'm surprised to read some of the answers to this thread because this scenario is precisely the reason checked exceptions exist. You could do something like:
private final static int MAX_RETRY_COUNT = 5;
//...
int retryCount = 0;
int angle = -1;
while(true)
{
try
{
angle = getAngle();
break;
}
catch(NoAngleException e)
{
if(retryCount > MAX_RETRY_COUNT)
{
throw new RuntimeException("Could not execute getAngle().", e);
}
// log error, warning, etc.
retryCount++;
continue;
}
}
// now you have a valid angle
This is assuming that something outside of the process changed in the meantime. Typically, something like this would be done for reconnecting:
private final static int MAX_RETRY_COUNT = 5;
//...
int retryCount = 0;
Object connection = null;
while(true)
{
try
{
connection = getConnection();
break;
}
catch(ConnectionException e)
{
if(retryCount > MAX_RETRY_COUNT)
{
throw new RuntimeException("Could not execute getConnection().", e);
}
try
{
TimeUnit.SECONDS.sleep(15);
}
catch (InterruptedException ie)
{
Thread.currentThread().interrupt();
// handle appropriately
}
// log error, warning, etc.
retryCount++;
continue;
}
}
// now you have a valid connection
I think you should investigate why getAngle() is throwing an exception and then resolve the problem. If this is random, like input from a sensor, maybe you should wait some time until calling again. You could also make getAngle() blocking, that means getAngle() will wait until a good result is acquired.
Ignoring how you're solving your problem you should have some kind of timeout mechanism, so you don't end up in an endlessloop. This supposes that you don't want to have an possibly infinite loop, of course.
You want to call a method as long as it throws an exception?
This is not programming. You should use the debugger and take a look at the real issue.
And you should never catch an exception without any message or logging!
Could you not have used recursion?
i.e.;
public int getAngleBlocking()
{
int angle;
try
{
angle = getAngle();
return angle;
}
catch(NoAngleException e)
{
return getAngleBlocking();
}
}
}
I would not recommend to do it that way, because when getAngle() never returns a valid value (always throws an exception for some reason) you end up in an endless loop. You should at least define a break condition (e.g. timeout) for this case.
In the end I opted for returning a NaN value, as this prevents careless use of Integer.MIN_VALUE somewhere else.
public float getAngle(boolean blocking)
{
while(true)
{
int dir = getDirection();
if(dir == 0 && !blocking)
return Float.NaN;
else
return (dir - 5) * 30;
}
}
Unless you are using a class that is entirely outside of your control, you really want to reconsider throwing an exception to indicate no angle.
Sometimes, of course, this is not possible either because the class is not yours, or, it is not possible to make dual use of the returned type as both the result or error status.
For example, in your case, assuming all integer (negative and 0) degrees are possible angles, there is no way for you to return an int value that indicates error and is distinct from a valid angle value.
But lets assume your valid angles are in range -360 -> 360 (or equiv. in radians). Then, you really should consider something like:
// assuming this ..
public static final int NO_ANGLE_ERROR = Integer.MIN_VALUE;
// do this
public int getAngleBlocking()
{
int angle;
do {
angle = getAngle();
}while(angle == NO_ANGLE_ERROR);
}
Never use Exceptions to handle flow logic in your code.
as suggested first check why you sometimes get the execption

Categories

Resources