Throws exception use in java



How to Throw Exceptions

Before you can catch an exception, some code somewhere must throw one. Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it’s always thrown with the throw statement.

As you have probably noticed, the Java platform provides numerous exception classes. All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program.

You can also create your own exception classes to represent problems that can occur within the classes you write. In fact, if you are a package developer, you might have to create your own set of exception classes to allow users to differentiate an error that can occur in your package from errors that occur in the Java platform or other packages.

You can also create chained exceptions. For more information, see the Chained Exceptions section.

The throw Statement

All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here’s an example of a throw statement.

Let’s look at the throw statement in context. The following pop method is taken from a class that implements a common stack object. The method removes the top element from the stack and returns the object.

The pop method checks to see whether any elements are on the stack. If the stack is empty (its size is equal to 0 ), pop instantiates a new EmptyStackException object (a member of java.util ) and throws it. The Creating Exception Classes section in this chapter explains how to create your own exception classes. For now, all you need to remember is that you can throw only objects that inherit from the java.lang.Throwable class.

Note that the declaration of the pop method does not contain a throws clause. EmptyStackException is not a checked exception, so pop is not required to state that it might occur.

Throwable Class and Its Subclasses

The objects that inherit from the Throwable class include direct descendants (objects that inherit directly from the Throwable class) and indirect descendants (objects that inherit from children or grandchildren of the Throwable class). The figure below illustrates the class hierarchy of the Throwable class and its most significant subclasses. As you can see, Throwable has two direct descendants: Error and Exception .

The Throwable class.

Error Class

When a dynamic linking failure or other hard failure in the Java virtual machine occurs, the virtual machine throws an Error . Simple programs typically do not catch or throw Error s.

Exception Class

Most programs throw and catch objects that derive from the Exception class. An Exception indicates that a problem occurred, but it is not a serious system problem. Most programs you write will throw and catch Exception s as opposed to Error s.

The Java platform defines the many descendants of the Exception class. These descendants indicate various types of exceptions that can occur. For example, IllegalAccessException signals that a particular method could not be found, and NegativeArraySizeException indicates that a program attempted to create an array with a negative size.

One Exception subclass, RuntimeException , is reserved for exceptions that indicate incorrect use of an API. An example of a runtime exception is NullPointerException , which occurs when a method tries to access a member of an object through a null reference. The section Unchecked Exceptions — The Controversy discusses why most applications shouldn’t throw runtime exceptions or subclass RuntimeException .

Источник

throw and throws in Java

throw

The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.

Syntax:

But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class. Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions.

The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.

Читайте также:  Cannot edit error writing

Output:

Another Example:

Output:

throws

throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.

Syntax:

In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways:

  1. By using try catch
  2. By using throws keyword

We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.

Output:

Explanation: In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute main() method which will cause InterruptedException.

Output:

Explanation: In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello Geeks

Another Example:

Output:

Important points to remember about throws keyword:

  • throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless.
  • throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program.
  • By the help of throws keyword we can provide information to the caller of the method about the exception.

Reference: Java – The complete Reference by Herbert Schildt

Источник

How to use the Throws keyword in Java (and when to use Throw)

Table of Contents

Both throw and throws are concepts of exception handling in Java. The throws keyword is used to declare which exceptions can be thrown from a method, while the throw keyword is used to explicitly throw an exception within a method or block of code.

The throws keyword is used in a method signature and declares which exceptions can be thrown from a method. The throws keyword can be useful for propagating exceptions in the call stack and allows exceptions to not necessarily be handled within the method that declares these exceptions.

On the other hand, the throw keyword is used within a method body, or any block of code, and is used to explicitly throw a single exception. The throw keyword can be useful for throwing exceptions based on certain conditions within a code block and for throwing custom exceptions.

Java Throws Keyword

The throws keyword in Java is used to declare exceptions that can occur during the execution of a program. For any method that can throw exceptions, it is mandatory to use the throws keyword to list the exceptions that can be thrown. The throws keyword provides information about the exceptions to the programmer as well as to the caller of the method that throws the exceptions.

The throws keyword allows exceptions to be propagated in the call stack. When a method declares that it throws an exception, it is not required to handle the exception. The caller of a method that throws exceptions is required to handle the exceptions (or throw them to its caller and so on) so that the flow of the program can be maintained.

Only checked exceptions are required to be thrown using the throws keyword. Unchecked exceptions don’t need to be thrown or handled explicitly in code.

Java Throws Example

Here is an example of a method that throws an exception, which is handled by the caller of the method:

In the above example, the “writeToFile” method throws an IOException and declares it using the throws keyword to its callers. The “main” method calls the “writeToFile” method and handles the exception within a try-catch block, and prints the exception stack trace to the console.

Java Throws Syntax

The throws syntax in Java is shown below:

As seen in the syntax above, all exceptions that can be thrown by a method should be declared in the method signature using the throws keyword. A method can throw multiple exceptions, which should be separated by a comma in the declaration.

Читайте также:  Visual studio code terminal error

Java Throw Keyword

The throw keyword in Java is used for explicitly throwing a single exception. This can be from within a method or any block of code. Both checked and unchecked exceptions can be thrown using the throw keyword.

When an exception is thrown using the throw keyword, the flow of execution of the program is stopped and the control is transferred to the nearest enclosing try-catch block that matches the type of exception thrown. If no such match is found, the default exception handler terminates the program.

The throw keyword is useful for throwing exceptions based on certain conditions e.g. if a user enters incorrect data. It is also useful for throwing custom exceptions specific to a program or application.

Unchecked exceptions can be propagated in the call stack using the throw keyword in a method. Checked exceptions can be propagated using the throw keyword when the method that throws the exception declares it using the throws keyword.

Java Throw Syntax

The throw syntax in Java is shown below:

A throwable object can be an instance or subclass of the Throwable class. All exceptions defined in Java are subclasses of Throwable.

Java Throw Example

In this example, the “addInteger” method throws an IllegalArgumentException using the throw keyword in case the “integers” ArrayList object already contains the integer passed.

Since IllegalArgumentException is a checked exception, it must be handled within the “addInteger” method or its caller. In this example, the “addInteger” method does not handle the exception and throws it to the caller using the throws keyword.

Therefore the caller, “main”, has to handle the IllegalArgumentException using a try-catch block.

Java Throw vs Throws

The table below lists the difference between the throw and throws keywords in Java:

Throw Throws
Used within a method (or constructor) Used with method (or constructor) signature
Used to throw an exception explicitly Used to declare exceptions
Can only throw a single exception Can declare multiple exceptions
Followed by a throwable instance Followed by an exception class name
Cannot be used to propagate checked exceptions by itself Can be used to propagate checked exceptions by itself

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Rollbar can help throw Java exceptions as well as track, analyze, and manage errors in real-time to help you to proceed with more confidence. Try it today!

Источник

BestProg

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.

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.

  • 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.

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:

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

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

Below is a demonstration of class usage in code.

The result of the program is as follows:

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.

In the above example, after declaration

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

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

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

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 – 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

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

Источник

Оцените статью
toolgir.ru
Adblock
detector