Question

So just got into the basics of try-catch statements in Java and I'm still a bit confused on some differences within the syntax.

Here is the code I'm trying to analyze and understand. What's the difference between using try then catch(Exception e) as compared to saying just throws or throw new?

From my understanding, a try and catch is basically a way to handle the error by outputting a message or passing to another method. However, I think I'm stuck on the syntax aspect of it.

Any constructive comments or simple examples clarifying this concept as well as whats going on with the sample code from my book would be appreciated.

/* Invalid radius class that contains error code */
public class InvalidRadiusException extends Exception {
     private double radius;

/** Construct an exception */
public InvalidRadiusException(double radius) {
       super("Invalid radius " + radius);
       this.radius = radius;
}

/** Return the radius */
public double getRadius() {
    return radius;
 }
}


public class CircleWithException {
/** The radius of the circle */

private double radius;

/** The number of the objects created */
private static int numberOfObjects = 0;

/** Construct a circle with radius 1 */
public CircleWithException() throws InvalidRadiusException {
       this(1.0);
  }

/** Construct a circle with a specified radius */
public CircleWithException(double newRadius) throws InvalidRadiusException {
          setRadius(newRadius);
          numberOfObjects++;
}

/** Return radius */
public double getRadius() {
     return radius;
}

/** Set a new radius */
public void setRadius(double newRadius)
    throws InvalidRadiusException {
if (newRadius >= 0)
  radius =  newRadius;
else
  throw new InvalidRadiusException(newRadius);
}

/** Return numberOfObjects */
public static int getNumberOfObjects() {
      return numberOfObjects;
}

/** Return the area of this circle */
public double findArea() {
    return radius * radius * 3.14159;
 }
}
Was it helpful?

Solution

Explanation

From the Java documentation:

[The try block] contains one or more legal lines of code that could throw an exception. (The catch and finally blocks are explained in the next two subsections.)

An exception is a special kind of object. When you write new Exception(), you are creating a new exception object. When you write throw new Exception() you are creating a new error, and then throwing it to the nearest try-catch block, aborting the rest of your code.

When you throw an exception, it gets caught by the try-catch block that it's nested in (inside of). That is, assuming the proper catch block for that exception is registered. If the code is not wrapped in a try-catch block, the program with automatically shut down as soon as an error is thrown. Use a try-catch around any code or method that can throw an error, especially because of user input (within reason).

Some exceptions have to be caught, others are optional to catch. (checked vs. unchecked).

When you add throws to a method signature, you are announcing to other methods that if they call that method, it has the potential to throw a checked exception (it is not necessary for unchecked). Notice how it's throws not throw. It's not doing an action, it's describing that it sometimes does an action.

You use this functionality when you don't want to catch the error inside that method, but want to allow the method's that call your method to catch the error themselves.

Exceptions are a way to make your program respond coherently to unexpected or invalid situations and are especially useful when user input is required, though it's also useful in other situations such as File input/output.

Examples

public CircleWithException() throws InvalidRadiusException {
       this(1.0);
}

Here, the CircleWithException() has the potential to throw an InvalidRadiusException (presumably, the this(1.0) sometimes throws an InvalidRadiusException.)

The code calling this method should have:

try {
    new CircleWithException(); // This calls the method above
} catch (InvalidRadiusException e) { // The object "e" is the exception object that was thrown.
    // this is where you handle it if an error occurs
}

As I said before, an Exception is just a specific type of object that extends Exception

/* Invalid radius class that contains error code */
public class InvalidRadiusException extends Exception {
     private double radius;

/** Construct an exception */
public InvalidRadiusException(double radius) {
       super("Invalid radius " + radius);
       this.radius = radius;
}

/** Return the radius */
public double getRadius() {
    return radius;
 }
}

The above code defines a new type of Exception specific to your program/application. There are many predefined exceptions in the Java Standard Library, but often you need to create your own.

To throw this exception, you first create an InvalidRadiusException object and then throw it:

throw new InvalidRadiusException(1.0);

OTHER TIPS

You can declare a method to throw an exception if you can't (or it's not convinient) to handle the exception inside the method.

In your case, you are calling the method setRadius inside the constructor. If you think that is convinient to handle the exception (that is thrown by setRadius) inside the constructor, you can use a try-catch clause:

public CircleWithException(double newRadius) throws InvalidRadiusException {
    try {
        setRadius(newRadius);
        numberOfObjects++;
    } catch (InvalidRadiusException e) {
        setRadius(0); // for example
    }
}

The catch block contains what you want to do if an exception were thrown. In this case, I'm setting the radius to 0, but you can change this.

Remember that it depends in your classes implementation and how you want them to work. If you don't want the constructor to handle this exception, you can throw it (as you are already doing) and handle it in other methods.

"throws" is a declaration that a method will throw certain exceptions. This is enforced by the java compiler for checked exceptions, and not for errors or unchecked exceptions.

"throw new" are two keywords in java so we can break it down...

  • "throw" is an operator that throws an exception
  • "new" is an operator that creates a new instance of an object

the "try" block allows you to execute methods that declare they throw exceptions, and that is where you use the "catch" clause, in order to catch those thrown exceptions.

Additionally there is also the try-with-resources block where you can use a try block to operate on a consumable resource(say, a stream) that implements AutoCloseable, and then close it.

There is also the "finally" clause to a try block, which allows you to execute cleanup or any other methods that MUST execute after a try block, regardless of whether exceptions occur or not.

There are two types of exceptions

1) Unchecked. These are defined by the Error and RuntimeException classes and all of their subclasses. Java does not force you to handle these exception in any way.

2) Checked. These are defined be the Throwable class and all of its subclasses that do not fall into the category defined in (1). Java forces you to handle these exceptions with a try/catch. If you call a method that can throw such an exception (defined with the throws keyword) outside of a try block your code will not compile.

throws : This is a way of declaring that a method can potentially throw an exception that must be caught with a try/catch. For example

public void doSomething() throws MyException { ... }

is a declaration of a method that can potentially throw an instance of MyException.

try/catch/finally : This is a way of handling exceptions that may be produced by some sort of code. The cody you are trying to run goes in the try block, the error handling code goes into the catch block. The optional finally block is something that will be executed regardless of whether or not an exception is thrown. In fact the finally block will be called even if you do a return inside your try or your catch. For example

try {
    doSomething();
} catch (MyException exception) {
    exception.printStackTrace();
}

or an example of using finally :

MyResource myResource = getMyResource();
try {
    myResource.open();
    doStuffWithMyResource(myResource);
} catch (Exception exception) {
    exception.printStackTrace();
} finally {
    if (myResource.isOpen()) {
        myResource.close();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top