Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using try-catch java

Tags:

java

try-catch

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;
 }
}
like image 454
zeesh91 Avatar asked Mar 25 '14 19:03

zeesh91


1 Answers

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);
like image 150
sinθ Avatar answered Sep 27 '22 17:09

sinθ