Abbey S Abbey S - 14 days ago 7
Java Question

Exception Class not working

I have a program that I'm trying to make throw a certain exception. I've created a custom Exception class here:

import java.io.*;

public class ShapeException extends Exception
{
public ShapeException(String message)
{
super(message);
}
}


Here is the class where I try and implement the Exception:

import java.io.*;

public class Circle
{
private double radius;

public Circle(double inRadius )
{
if(inRadius < 0.0)
{
throw new ShapeException("Shape Exception Occurred...");
}
else
{
radius = inRadius;
}
}

public double getRadius()
{
return radius;
}

public void setRadius(double newRadius)
{
if(newRadius < 0.0)
{
throw new ShapeException("Shape Exception Occurred...");
}
else
{
radius = newRadius;
}
}

public double area()
{
return Math.PI * radius * radius;
}

public void stretchBy(double factor )
{
if(factor < 0.0)
{
throw new ShapeException("Shape Exception Occurred...");
}
else
{
radius = radius * factor;
}
}

public String toString()
{
return "Circle Radius: " + radius;
}
}


However, this will not compile and gives me errors telling me that my shape exception error must be caught or declared to be thrown. What am I doing wrong? Is this not declared?

Answer

In java whenever you throw a checked exception you need to declare it in the method signature with throws keyword. Below is the code snippet which are not having any compilation errors because each method has throws declaration wherever ShapeException is thrown.

public class Circle {
    private double radius;

    public Circle(double inRadius) throws ShapeException {
        if(inRadius < 0.0) {
            throw new ShapeException("Shape Exception Occurred...");
        } else {
            radius = inRadius;
        }
    }

    public double getRadius() {
        return radius;
    }

    public void setRadius(double newRadius) throws ShapeException {
        if(newRadius < 0.0) {
            throw new ShapeException("Shape Exception Occurred...");
        } else {
            radius = newRadius;
        }
    }

    public double area() {
        return Math.PI * radius * radius;
    }

    public void stretchBy(double factor) throws ShapeException {
        if(factor < 0.0) {
            throw new ShapeException("Shape Exception Occurred...");
        } else {
            radius = radius * factor;
        }
    }

    @Override
    public String toString() {
        return "Circle Radius: " + radius;
    }
}