Java. Exceptions. Operators throw, throws. Examples




Java. Exceptions. Operators throw, throws. Examples


Contents


The study of this topic is based on the use of the following topics:

Search other websites:

1. What is the purpose of the keyword throw? General form

An exception can be generated:

  • by the Java Runtime Environment;
  • by the application. In this case, the program should use the throw statement.

The general form of the throw statement is as follows.

throw instance;

here instance – an object of class Throwable or a subclass derived from it. More details about the Throwable class can be found here.

If the throw statement is used in a try…catch block, then the general form of the block is as follows.

...
try {
    // ...
    throw new ThrowableClass(parameters); // if an exceptional situation, you throw an exception
    // ...
}
catch (ThrowableClass e) {
    // handle the exception
    // ...
}
...

here

  • ThrowableClass – class derived from the class Throwable or RunTimeException;
  • e is an instance of the class that corresponds to the exception being caught;
  • parameters – the parameters of the constructor of the class ThrowableClass. As a rule, constructors of classes derived from Throwable or RunTimeException have two variants of implementation: without parameters or with one string parameter that describes an exceptional situation.

In line

throw new ThrowableClass(parameters);

an exception is thrown using the new operator, which allocates memory and calls a constructor. For all standard exceptions, there are two constructors:

  • default constructor. This constructor does not contain parameters;
  • constructor with one parameter, which is a string. The string contains information about the exception. For example, the string “division by zero”.

   

2. An example of generating an exception using the throw operator in a try block. Creating a class that solves a quadratic equation

An exception is thrown using the throw keyword, which can be found in a try block (manually generating an exception). For example, the following code shows an example of generating an exception manually using the throw tool.

The QuadraticEquation class is declared which solves a quadratic equation.

The class declares the following elements:

  • internal variables a, b, c which are the coefficients of the equation;
  • internal variables x1, x2 which are solutions of the equation (if the equation has a solution);
  • class constructor;
  • method Solution(). This method uses the processing of possible exceptions: division by 0 and the root of a negative number.

The class text is as follows:

// throwing an exception with a throw statement
// the solution of the quadratic equation
class QuadraticEquation {
    double a,b,c,x1,x2;

    // constructor
    QuadraticEquation(double a, double b, double c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    // method that solves quadratic equation
    void Solution() {
        double d; // discriminant

        try {
            d = b*b - 4*a*c;

            // it is necessary to take into account the division by 0
            if (a==0)
                throw new ArithmeticException("Division by 0."); // create an exception

            // take into account the root of a negative number
            if (d<0)
                throw new ArithmeticException("The equation has no roots."); // create an exception

            x1 = (-b - Math.sqrt(d))/(2*a);
            x2 = (-b + Math.sqrt(d))/(2*a);

            System.out.println("x1 = " + x1);
            System.out.println("x2 = " + x2);
        }
        catch (ArithmeticException e) {
            System.out.println(e); // throw an exception created in a try block
        }
    }
}

The Solution() method intercepts two exceptional situations:

  • division by 0;
  • root of a negative number.

To do this, using the throw operator creates a corresponding instance of the ArithmeticException class. The ArithmeticException class is a subclass of the RuntimeException class. The class ArithmeticException is used if an arithmetic error has occurred. In our case, we have arithmetic errors of two types:

  • division by 0;
  • the root of the negative number.

Therefore, in the try block, a corresponding instance of the exception is created with a string describing the error

...
// consider division by 0
if (a==0)
    throw new ArithmeticException("Division by 0.");
if (d<0)
    throw new ArithmeticException("The equation has no roots.");
...

Handling any of the errors in the catch statement is standard. Therefore, the text of the exception description is displayed.

...
catch (ArithmeticException e) {
    System.out.println(e); // throw an exception created in a try block
}
...

Below is a demonstration of class usage in code.

public class Train02 {
    public static void main(String[] args) {
        // create an instance of class
        QuadraticEquation qE = new QuadraticEquation(1,1,1);
        qE.Solution(); // call a method that solves the equation
        System.out.println("-------------------------");

        // create another instance of the class
        QuadraticEquation qE2 = new QuadraticEquation(0,3,5);
        qE2.Solution();
        System.out.println("-------------------------");

        QuadraticEquation qE3 = new QuadraticEquation(2,3,-5);
        qE3.Solution();
    }
}

The result of the program is as follows:

java.lang.ArithmeticException: The equation has no roots.
-------------------------
java.lang.ArithmeticException: Division by 0.
-------------------------
x1 = -2.5
x2 = 1.0

   

3. What types are forbidden to use for throwing exceptions using throw statement?

To generate exceptions using throw statement may not be used:

  • primitive types (for example int, char);
  • classes, excluding of classes inherited from the class Throwable. For example, it is forbidden to use the class String or other classes.

   



4. How to create your own exception class? Example

To create your own exception class, you need to inherit this class from the Exception class. After the class is inherited from the Exception class, it is already part of the Java exception system and can be used as other exception classes (for example, ArithmeticException, ArrayIndexOfBoundsException, etc.).

More details about using the Exception class and other classes are described in the topic:

If the class is inherited from the Exception class, then it is not even necessary to implement some additional operations in this class. In any case, the exception that corresponds to this class will be correctly caught in the catch block.

The Exception class does not contain methods. However, this class is inherited from the Throwable class. In the Throwable class, there are a number of methods available that can be overridden by exceptions.

Example. For the purpose of the demonstration, a NegativeNumberException class is declared. In our case, this class is an exception that is generated when the number is negative. The class declares:

  • internal variable value. This variable is optional and is introduced for the purpose of demonstration;
  • constructor, which is optional;
  • the toString() method, which overrides the same name method of the Throwable class. This method displays the corresponding message.
// Declare a class that is derived from the Exception class
// This class is part of the Java exception system.
class NegativeNumberException extends Exception {
    private double value;

    // some class constructor
    NegativeNumberException(double _value) {
        value = _value;
    }

    // the overridden toString () method of the Throwable class,
    // This method displays exception information of the type NegativeNumberException.
    public String toString() {
        String msg = "Exception: " + value + " is a negative number!!!";
        return msg;
    }
}

public class Train04 {
    public static void main(String[] args) {
        // the generation of the type of exception NegativeNumberException is demonstrated
        double value;

        try {
            value = -5; // negative number

            // if a negative number,
            // throw an exception of type NegativeNumberException
            if (value<0)
                throw new NegativeNumberException(value);
        }
        catch (NegativeNumberException e) {
            // display information about the exception
            // method toString() of the class NegativeNumberException is called
            System.out.println(e);
        }
    }
}

In the above example, after declaration

class NegativeNumberException extends Exception {
    // ...
}

the NegativeNumberException class becomes part of the Java exception class hierarchy. Therefore, it can be used in the catch block of the try…catch construction.

In the function main(), an exception of the type NegativeNumberException is specially generated in the string

...
if (value<0)
    throw new NegativeNumberException(value);
...

As a result, the program goes into the catch block, which displays information about the exception

...
catch (NegativeNumberException e) {
    System.out.println(e);
}
...

In fact, the toString() method of the NegativeNumberException class is called. If the toString() method were not overridden in the NegativeNumberException class, then the Throwable class toString() method would be called.

The result of the program

Exception: -5.0 is a negative number!!!

   

5. What is the purpose of the throws keyword? General form

The throws statement is used in a method declaration to tell the calling code that this method can generate an exception that it does not handle. This applies to all exceptions except:

  • classes Error and RuntimeException;
  • any subclasses that inherit from the Error and RuntimeException classes.

The general form of using the throws statement in a method is

 

type MethodName(parameters) throws exceptions_list {
    // ...
}

here

  • type – the type that methodName() returns;
  • MethodName – the name of method;
  • parameters – method parameters;
  • exception_list – list of types (classes) of exceptions separated by commas. This is a list of exceptions that can be generated in the MethodName() method.





   

6. An example of using the throws statement for the method that throws an exception

The example declares the NegativeNumberException class derived from the Exception class. This class is an exception class.

Also declared class DemoThrows, which contains SumItems() method that can throw an exception of type NegativeNumberException.

The program code for the classes is as follows

// Declare a class that is derived from the Exception class
// After that, this class is part of the Java exception system
class NegativeNumberException extends Exception {
    private double value;

    // constructor
    NegativeNumberException(double _value) {
        value = _value;
    }

    // the overridden toString () method of the Throwable class,
    // This method displays exception information of the type NegativeNumberException.
    public String toString() {
        String msg = "Exception: " + value + " is a negative number!!!";
        return msg;
    }
}

// exception demonstration
class DemoThrows {
    int SumItems(int A[]) throws NegativeNumberException {
        int i, sum=0;
        for (i=0; i<10; i++) {
            // if the index is outside the array, then throw an exception
            if (i>A.length)
                throw new ArrayIndexOutOfBoundsException("Index out of array bounds.");
            if (A[i]<0)
                throw new NegativeNumberException((double)A[i]);
            sum += A[i];
        }
        return sum;
    }
}

public class Train04 {
    public static void main(String[] args) {
        // invoke the SumItems() method from the DemoThrows class
        int M[] = { 1, -2, 3, 4, 5, 6, 7 };
        DemoThrows dt = new DemoThrows(); // create an instance of class DemoThrows
        int summ=0;

        try {
            // invoke the method that throws
            // a NegativeNumberException exception
            summ = dt.SumItems(M);
        }
        catch (NegativeNumberException e) {
            System.out.println("Intercepted exception: "+e);
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Intercepted exception: " + e);
        }
        finally {
            System.out.println("Summ = " + summ);
        }
    }
}

An exception may occur in a method that will throw an exception of type NegativeNumberException. Therefore, the declaration of the method contains the keyword throws with the name of the exception

...
int SumItems(int A[]) throws NegativeNumberException {
    ...
}
...

The result of the program

Intercepted exception: Exception: -2.0 is a negative number!!!
Summ = 0

   


Related topics