I know how to assert that an Exception is thrown. But, how can I assert that an Exception was thrown and it was successfully caught? For example, say I have a method which should throw a particular type of exception for invalid inputs
public static void myMethod(String value) {
try {
someExternalMethod(value);// can throw IllegalArgumentException
} catch (IllegalArgumentException e) {
System.out.println("Let me handle it differently");
} catch (Exception e) {
System.out.println("Not IllegalArgumentException");
}
}
Now I want to assert that for some values the method indeed has thrown 'IllegalArgumentException' and not some other Exception.
In the context of testing myMethod you cannot (and more importantly, you should not want to) check that someExternalMethod has thrown IllegalArgumentException. In fact, your tests of myMethod should not assume that a call of someExternalMethod has been made: it is an implementation detail of myMethod.
The very reason myMethod catches these exceptions is to hide them from its callers. You should check that these exceptions are hidden from you by passing values that cause them, and verifying that nothing is thrown in both cases.
Testing someExternalMethod, along with the exceptions that it throws, is the task accomplished by testing someExternalMethod, not myMethod.
You're missing the important point of unit testing - tests should test behaviour, not implementation.
Given this assumption you should be testing the behaviour of myMethod is as expected when an IllegalArgumentException occurs. It's hard to say any more than that with the method you've shown given the parameter, a single String is immutable, there is no return value and no exceptions are thrown.
A better example might be this method (which is a little contrived to demonstrate the point):
public double divide(int numerator, int denominator)
{
try
{
return numerator / denominator;
}
catch (ArithmeticException e)
{
return Double.NaN;
}
}
Where your tests would assert that the division is correct and that when an error occurs NaN is returned, like this:
#Test
public void testDivide()
{
assertEquals(2.0, divide(4, 2), 0);
}
#Test
public void testDivideByZero()
{
assertTrue(Double.isNaN(divide(1, 0));
}
You could then re-write the divide method like this:
public double divide(int numerator, int denominator)
{
if (denominator == 0)
{
return Double.NaN;
}
else
{
return numerator / denominator;
}
}
And the tests would confirm the operation of my system because the behaviour of the divide method remains unchanged.
catch blocks are evaluated in the order they are.
Your code works fine: in case of IllegalArgumentException, Exception block will be ignored.
Mock method someExternalMethod(value) to force throw Exception
Test method myMethod, checking that is not throwing Exception:
#Test
public void testMyMethod() {
try {
myMethod("value");
} catch (Exception ex) {
Assert.fail();
}
}
Related
I have this method:
public int addInt(int x, int y){
try{
if(x<1 || y<1){
throw new InvalidValueExeption();
}
} catch(InvalidValueExeption i){
System.out.println(i);
}
return x+y;
}
InvalidValueExeption is a custom exception. So I wanted to test this:
#Test
public void test(){
AddClass a = new AddClass();
boolean thrown = false;
try{
a.addInt(-2, 3);
} catch(InvalidValueException e){
thrown=true;
}
assertTrue(thrown);
}
I can't run this test, because it says Exception exception.InvalidValueException is never thrown in the corresponding try block.
What am I doing wrong?
Your addInt() method doesn't throw InvalidValueException (*). Inside the method, you do throw it, but you catch it before it can "leave" your method. So, for the outside world, there is no InvalidValueException coming from your method.
Then, correctly the compiler tells you that there's no point in catching the InvalidValueException.
So, instead of immediately catching the exception inside your method, declare the method to throw InvalidValueException:
public int addInt(int x, int y) throws InvalidValueException {
if (x < 1 || y < 1) {
throw new InvalidValueException();
}
return x + y;
}
Rationale:
Exceptions are meant to tell the caller (**) of some method that it couldn't fulfill its task, i.e. your addInt() method is designed to add only positive numbers. And if someone tries it with a number below 1, the method answers with the exception instead of returning a value, thus saying: "Hey, something went wrong, so I can't give you an answer (and the problem description is [the exception with its message and so on])."
( * ) I assume, the missing "c" is just a typo, and you don't have two different exception classes.
( ** ) That's important. I'm not talking about System.out.println(), as that's telling something to the user, not the caller.
If InvalidValueExeption is a checked exception then the compiler will complain because addInt is not declared to throw InvalidValueExeption.
If InvalidValueExeption is not a checked exception then the test will fail because addInt swallows the InvalidValueExeption.
There's also a possible typo in your question: addInt() throws InvalidValueExeption whereas test() tries to catch InvalidValueException. In the former case exception is spelled "Exeption", in the latter case it is spelled "Exception", note the missing "c".
The following approach will work:
public int addInt(int x, int y) {
if (x < 1 || y < 1) {
throw new InvalidValueException();
}
return x + y;
}
#Test(expected = InvalidValueException.class)
public void test(){
AddClass a = new AddClass();
a.addInt(-2, 3);
}
First of i think your InvalidValueExeption is a subtype of RuntimeException.
RuntimeException and its subclasses are unchecked exceptions.
Unchecked exceptions do not need to be declared in a method or
constructor's throws clause if they can be thrown by the execution of
the method or constructor and propagate outside the method or
constructor boundary.
So if you need to indicate that you throw an InvalidValueExeption or inherit Exception instead.
Here the exception is declared on your method and thrown :
public int addInt(int x, int y) throws InvalidValueExeption {
try {
//..
throw new InvalidValueExeption();
} catch (InvalidValueExeption e) {
// do some logging the throw back at you
throw e;
}
}
This question already has answers here:
Java Compiler Error: Missing Return Statement
(2 answers)
Closed 4 years ago.
I'm using the code below in a Triangle class to allow the user to set the first, second, or third point of a declared Triangle.
public Point get(String p) throws IllegalArgumentException {
IllegalArgumentException e = new IllegalArgumentException();
try {
if (p == "first") { return first; }
else if (p == "second") { return second; }
else if (p == "third") { return third; }
else { throw e; }
}
catch (e) {
System.out.println("Error: " + e);
}
}
The compiler is telling me:
Triangle.java:41: error: missing return statement
}
^
But I thought the point of the catch statement was to be able to catch an error and return a string describing the error, without having to worry about matching the function's return type.
Because you're missing a return statement.
The method declares that it returns something, so it must return something (or throw an exception). The compiler can't guarantee that any of the return statements in the try block will be reached if an exception is thrown before any of them execute. So the catch block also needs to return something (or throw an exception, or return something after the try/catch construct entirely).
Edit: Looking again, you're also potentially missing a return in the try block. (If you don't have one after the entire try/catch structure.) What if none of the conditions in the if/else structure are satisfied? Nothing is returned. Which is invalid.
Basically, all logical paths must result in a valid exit of the method. You've missed two such paths.
You're not returning anything in your function on several paths.
But I thought the point of the catch statement was to be able to catch an error and return a string describing the error, without having to worry about matching the function's return type.
That's not at all what a try-catch does, and moreover your function is declared to return a Point not a String.
try-catch simply "catches" a Throwable (Error or Exception) and allows you to run some code when it is thrown instead of simply terminating the application with an Uncaught Exception/Error.
You need to return some value from your function after the try-catch there is no way to return a string, nor is there a language construct in place that behaves like you've explained your understanding of try-catch.
Also your code cna't actually throw an IllegalArgumentException so your catch block will never get called. In this case, it sounds like what you want is instead something like this
public Point get(String p) throws IllegalArgumentException {
if (p == null) { throw new IllegalArgumentException(); }
if (p.equals("first")) { return first; }
else if (p.equals("second")) { return second; }
else if (p.equals("third")) { return third; }
else { throw new IllegalArgumentException(); }
}
The code could then be called like so
Point p;
try {
p = get("notFirst");
} catch (IllegalArgumentException ex) {
//oh no, we gave a bad argument, and the method told us nicely.
}
You are missing two parts:
1. A return statement in try block for else condition
2. Catch block doesn't lead to a return statement or a throw statement
I don't know if type of first, second, third variables are string or Point, but you should return with Point, because your function is :
public Point get(String p) {
...
}
You have three if statements. What happens when the input doesn't satisfy any of those? Your method doesn't have a return statement for that case.
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.
Consider this simple program. The program has two files:
File Vehicle.java
class Vehicle {
private int speed = 0;
private int maxSpeed = 100;
public int getSpeed()
{
return speed;
}
public int getMaxSpeed()
{
return maxSpeed;
}
public void speedUp(int increment)
{
if(speed + increment > maxSpeed){
// Throw exception
}else{
speed += increment;
}
}
public void speedDown(int decrement)
{
if(speed - decrement < 0){
// Throw exception
}else{
speed -= decrement;
}
}
}
File HelloWorld.java
public class HelloWorld {
/**
* #param args
*/
public static void main(String[] args) {
Vehicle v1 = new Vehicle();
Vehicle v2 = new Vehicle();
// Do something
// Print something useful, TODO
System.out.println(v1.getSpeed());
}
}
As you can see in the first class, I have added a comment ("// throw exception") where I would like to throw an exception. Do I have to define my own class for exceptions or is there some general exception class in Java I can use?
You could create your own Exception class:
public class InvalidSpeedException extends Exception {
public InvalidSpeedException(String message){
super(message);
}
}
In your code:
throw new InvalidSpeedException("TOO HIGH");
You could use IllegalArgumentException:
public void speedDown(int decrement)
{
if(speed - decrement < 0){
throw new IllegalArgumentException("Final speed can not be less than zero");
}else{
speed -= decrement;
}
}
Well, there are lots of exceptions to throw, but here is how you throw an exception:
throw new IllegalArgumentException("INVALID");
Also, yes, you can create your own custom exceptions.
A note about exceptions. When you throw an exception (like above) and you catch the exception: the String that you supply in the exception can be accessed throw the getMessage() method.
try{
methodThatThrowsException();
}catch(IllegalArgumentException e)
{
e.getMessage();
}
It really depends on what you want to do with that exception after you catch it. If you need to differentiate your exception then you have to create your custom Exception. Otherwise you could just throw new Exception("message goes here");
The simplest way to do it would be something like:
throw new java.lang.Exception();
However, the following lines would be unreachable in your code. So, we have two ways:
Throw a generic exception at the bottom of the method.
Throw a custom exception in case you don't want to do 1.
Java has a large number of built-in exceptions for different scenarios.
In this case, you should throw an IllegalArgumentException, since the problem is that the caller passed a bad parameter.
You can define your own exception class extending java.lang.Exception (that's for a checked exception - these which must be caught), or extending java.lang.RuntimeException - these exceptions does not have to be caught.
The other solution is to review the Java API and finding an appropriate exception describing your situation: in this particular case I think that the best one would be IllegalArgumentException.
It depends. You can throw a more general exception, or a more specific exception. For simpler methods, more general exceptions are enough. If the method is complex, then, throwing a more specific exception will be reliable.
i wrote an function like
public static boolean check()throws Exception
{
if(a=="asd")
return true;
else
return false;
}
this works fine
but if i use
public static boolean check()
{
try
{
if(a=="asd")
return true;
else
return false;
}
catch(Exception e)
{
}
}
it says you need to return an value,,,, is there is any difference between these two???
you need to return something in the catch, a method always need to return something, even in catch, unless you throw/rethow an exception.
Yes, there is a difference. Your second code block will catch any exception from the if statement and swallow it, and then resume running after the catch block. But there is no return statement there, so if there is any exception, the function will have no return value.
The first code block, on the other hand, uses throws to indicate that Exception descendants may escape from it instead of being caught, so it doesn't need to catch and handle anything itself, and the compiler is prepared to allow the function to not return anything (due to exiting early from an exception).
Java has methods, not functions. So you didn't write a function, but a method. Also, comparing strings with == does not work in Java. You have to call the equals() method instead:
if (a.equals("asd"))
The problem in your second piece of code is this: What happens if an exception occurs? The content of the catch block is executed, and after that the rest of the method is executed. Note that there is no code after the catch block. But the method requires that you return a boolean - you're missing a return statement. Change it like this:
public static boolean check()
{
try
{
if (a.equals("asd"))
return true;
else
return false;
}
catch(Exception e)
{
}
// You need to add a return statement here
return false;
}
There are some more comments that can be made about your code.
First of all, it's always a bad idea to leave a catch block empty. Because when an exception is caught, nothing will happen, and you'll never know that something went wrong. Always handle exceptions appropriately.
Also, code like this:
if (a.equals("asd"))
return true;
else
return false;
can be simplified like this:
return a.equals("asd");
The result of the expression a.equals("asd") is already a boolean; why would you check again if it's true or false and then return true or false?
Not all paths in the code will return a value. Since you have a catch there, if an exception is thrown, no value will be returned because the code in the catch will execute.
I think you should return the value at the end of function after catch. Try to store result in one boolean variable and return that variable after catch. This may solve your problem
A premise:
a=="asd" is not 'wrong' but probably it is better to use a.equals("asd") because == compares pointers, not equality. For example ("asd"=="asd") == false but ("asd".equals("asd")) == false
If if(a=="asd") throws an exception, the flow goes in the catch, and then it exits without ever finding the return statement. the correct code could have a return statement inside the catch block
Jesper's answer pretty much covers it. I needed to show some code so therefore this separate answer.
You will have to decide in each situation how to handle exceptions. Jesper and LordSAK both chose to return 'false'. A problem with this is that you can't distinguish the error condition from the case that 'a' is not equal to "asd".
A possible solution is to change the method's return type to Boolean (the Object version of the primitive boolean) and return 'null' in case of an exception
public static Boolean check() {
try {
return "asd".equals(a);
}
catch(Exception e) {
return null;
}
}
Another option is to re-throw your exception as an unchecked exception:
public static boolean check() {
try {
return "asd".equals(a);
}
catch(Exception e) {
throw new RuntimeException("Problem during check", e);
}
}
A drawback of this approach is that the code calling your check() method does not expect a runtime exception to be thrown. Because this type of exception is unchecked the developer will not get a compiler warning if he doesn't surround the call to check() with try-catch.
A third option is to just declare the exception and let your calling code handle it. A full example:
import org.apache.log4j.Logger;
public class Checker {
private static final Logger LOG = Logger.getLogger(Checker.class);
private String a;
public Checker(String value) {
a = value;
}
public boolean check() throws Exception {
return "asd".equals(a);
}
public static void main(String[] args) {
Checker app = new Checker("Stackoverflow");
try {
app.check();
}
catch(Exception e) {
LOG.error("Problem during check", e);
}
}
}
An advantage is that you don't have to decide which value check() returns in case of an error, but instead you just return the error itself. This is actually the whole idea of 'throwing' exceptions.
As a rule of thumb: if you can't handle an exception within the method itself, then throw it and let the calling code deal with it.
An example from the wild: A method handling an exception itself.
private static final long DEFAULT_TIMEOUT = 60000;
public long getTimeout(String timeoutArg) {
try {
return Long.parseLong(timeoutArg);
}
catch(NumberFormatException e) {
return DEFAULT_TIMEOUT;
}
}
NB: I didn't compile or run any of this code, so there might be typos.