Java method declare exception

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.

Читайте также:  Таблица в консоль python

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.

throw someThrowableObject;

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.

public Object pop() < Object obj; if (size == 0) < throw new EmptyStackException(); > obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; >

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 .

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 .

Источник

Class Exception

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor’s throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

Constructor Summary

Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause ).

Method Summary

Methods declared in class java.lang.Throwable

Methods declared in class java.lang.Object

Constructor Details

Exception

Constructs a new exception with null as its detail message. The cause is not initialized, and may subsequently be initialized by a call to Throwable.initCause(java.lang.Throwable) .

Exception

Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently be initialized by a call to Throwable.initCause(java.lang.Throwable) .

Exception

Constructs a new exception with the specified detail message and cause. Note that the detail message associated with cause is not automatically incorporated in this exception’s detail message.

Exception

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause ). This constructor is useful for exceptions that are little more than wrappers for other throwables (for example, PrivilegedActionException ).

Exception

protected Exception (String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)

Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

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

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

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:

public static void writeToFile() throws IOException < BufferedWriter bw = new BufferedWriter(new FileWriter("myFile.txt")); bw.write("Test"); bw.close(); >public static void main(String[] args) < try < writeToFile(); >catch (IOException ioe) < ioe.printStackTrace(); >>

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:

type method (arguments) throws Exception1, Exception2, …

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.

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

private static List integers = new ArrayList(); public static void addInteger(Integer value) throws IllegalArgumentException < if (integers.contains(value)) < throw new IllegalArgumentException("Integer already added."); >integers.add(value); > public static void main(String[] args) < try < addInteger(1); >catch (IllegalArgumentException iae) < iae.printStackTrace(); >>

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

Rollbar in action

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!

Источник

Оцените статью