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;
}
}
Related
How do you write a method that has "throws IllegalArgumentEception" in the method declaration. Such like this one: If I were to only return d if d>0 otherwise throw an IllegalArgumentException, how would I do that? Do you use try{} and catch{} ?
public double getPrice(double d) throws IllegalArgumentException {
}
You can do that simply at the beginning of the method:
public double getPrice(double d) throws IllegalArgumentException {
if(d <= 0) {
throw new IllegalArgumentException();
}
// rest of code
}
Also the throws IllegalArgumentException is not really needed in the declaration of the method. This must only be done with checked exceptions. But IllegalArgumentException belongs to the unchecked exceptions.
For more information about those I recommend reading this other question.
You should check the condition and if it doesn't meet throw the exception
Sample code:
public double getPrice(double d) throws IllegalArgumentException {
if (d <= 0) {
throw new IllegalArgumentException("Number is negative or 0");
}
//rest of your logic
}
You can learn more about Java Exception here.
i m writing a very simple java class and i faced a weird problem, i know there are many simple way to resolve it but now i have a doubt
public class Frazione {
private int num;
private int den;
public Frazione(int x, int y) throws FrazioneException {
if (y == 0) {
throw new FrazioneException();
}
num = x;
den = y;
}
/*public Frazione(int x){ THAT'S HOW IT SHOULD BE BASED
ON THE EXCERCISE BUT IT WON'T
COMPILE BECAUSE THIS ISN'T THE
FIRST STATEMENT
try{
this(x,1);
}catch(FrazioneException e){
System.err.print("errore: "+e);
}
}*/
/*public Frazione(int x){
this(x,1); IF I TRY THIS WAY I'LL BE IN
AN UNREPORTED EXCEPTION PROBLEM
}*/
public int getNum() {
return num;
}
public int getDen() {
return den;
}
}
there's a way to use try and catch with this() statement?
Yes, this doesn't work. You'd have to fulfill two contradictory requirements:
the this call has to be the first statement
the this call has to be in a try..catch statement.
So this can't be solved.
What you could do:
If you want to throw a checked exception in the constructor, throw it also in the other one. But that doesn't make real sense, because it will never been thrown, because you never pass y=0
Convert FrazioneException to a runtime exception and remove throws.
Try to solve your requirement without throwing an exception from the constructor (I usually avoid that because it often causes too much trouble. Like the one you have)
If there are multiple constructors and you are using this keyword within a constructor to call another constructor, the invocation of another constructor (this()) must be the first line of the constructor.
In java predefined Exceptions throws automatically. like,
int a=10, b=0;
c = a/b;
throws ArithmeticException
int a[3] = {1, 2, 3};
int b = a[4];
throws ArrayOutOfBoundException
wherein in case of user-defined exceptions we should create an object of that Exception class and throw it manually.Can I make my own Exception to behave like the above two cases?
Can I make my own Exception to behave like the above two cases?
No, it would have to be built into the JVM.
You may, but you have to catch the original and then throw your own.
try {
int a=10, b=0;
int c=a/b;
catch (Exception e){
//disregard exception, throw your own
throw new MyCustomException("My Custom Message");
}
Or, if you have a condition where you want to throw an exception on a case where an exception wouldn't normally exist, you just throw it!
// In this case, only move forward if a < b
int a = 10, b = 0;
if (a >= b)
throw new MustBeLessThanException("a must be less than b!");
Or something silly like that.
Be sure to make the custom class extend Exception or one of the subclasses.
No, all you can do is catch and then throw your own:
try {
int a=10, b=0;
c = a/b;
} catch (ArithmetikException e) {
throw MyException("Bad!", e); // pass in e to getr a meaningful stacktrace
}
But I really wouldn't recommend that (except in cases where you have to, ie. when implementing an interface that doesn't declare an exception that might be thrown in your code). But then again, your example both are RuntimeExceptions (which are unchecked) and those don't have to be declared.
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 am using Gson to parse Json. What I don't understand what the return type will be if you don't catch the Runtime Exception. I was expecting it to be null, but it is not null when evaluating with a simple if statement.
My code looks something like this:
public X x(final String jsonString) {
return gson.fromJson(jsonString, X.class);
}
then from another function I call the function:
public void y() {
final X x = x();
if (x == null) {
System.out.println("x == null");
}
}
I was expecting x to be null, but it isn't because the print statement is not called? What is the value of x? I have solved my problem by using a catch block in the x() function and returning null from inside the catch block. But I am just wondering what the value of function x() is(if any?)? Hopefully I make any sense at all.
If x() is throwing an exception, the x variable remains uninitialized, since the control flow was interrupted. Without a try/catch, the exception keeps going up the stack and x is never usable. With a try/catch, x is only valid within the block, so if an exception happens it won't be usable.
If you try to do something like:
X x;
try {
x = x();
} catch(RuntimeException e) {}
if (x == null) {
...
you'll get the error "variable x might not have been initialized", since control flow can bypass the assignment