What is the problem here? I am just simply trying to catch a custom exception depending on a if statement in my constructor, the entire code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package question3_test;
/**
*
* @author jackandjill
*/
public class Triangle2
{
private int side1, side2, side3;
private double area;
private String message;
public int getSide1()
{
return side1;
}
public void setSide1(int s1)
{
side1 = s1;
}
public int getSide2()
{
return side2;
}
public void setSide2(int s2)
{
side2 = s2;
}
public int getSide3()
{
return side3;
}
public void setSide3(int s3)
{
side3 = s3;
}
public Triangle2(int a,int b,int c) throws InvalidValueException
{
setSide1(a);
setSide2(b);
setSide3(c);
try
{
if (!(side1 + side2 > side3) && (side2 + side3 > side1)&& (side1 + side3 > side2))
throw new InvalidValueException("Invalid Value");
}
catch (InvalidValueException excep)
{
message = excep.getMessage();
//throw new InvalidValueException(message);
}
public double findArea(int side_1, int side_2, int side_3)
{
int s, a, b,c;
a = side_1;
b = side_2;
c = side_3;
s = ((a + b + c)/2);
area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
//area =
return area;
}
}
}
The problem is at my catch statement, it is underlined in red and says never thrown in the corresponding try statement
You can’t throw an Exception class like in the below code: –
You have to make a new instance of your exception, and then throw it: –
But, still there is some logic problem in your code. You have declared your
Exceptionto be throws, but at the same time, you are handling it in thecatchblock itself. Why would you do that?UPDATE: –
As per your modified post: –
Since you are no-where throwing any Exception in your
try block, thecatch blockwill complain about that..If you want to
throwan exception andcatchit in place, use it like this: –And suppose you are using it from your
mainmethod, you should have atry-catchblock there, to handle the declared exception in constructor.: –If you handle the exception in your method only, you should not declare it in your method declaration.. But if you are not handling it, then you must declare that exception to be thrown.
An exception should be either handled, or declared to be thrown (In which case, you should actually throw that exception), but never both
See This tutorial for more about Exception: – http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html