Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet171/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   167   168   169   170   171   172   173   174   ...   245
Bog'liq
Java 17 Recipes

9-3. Throwing Exceptions
 Problem
You want to abort the execution of the current code path by throwing an exception if a 
certain situation occurs within your application.
 Solution
Use the throw keyword to throw a specified exception when the situation occurs. Using 
the throw keyword, you can signal the current thread to look for try/catch blocks (at the 
current level and up the stack), which can process the thrown exception. In the following 
Chapter 9 exCeptions and Logging


335
example, the callSomeMethodThatMightThrow throws a NullPointerException 
(RuntimeException type) if the parameter passed in is null.
public class Recipe9_3 {
public static void main(String[] args) {
Recipe9_3 recipe = new Recipe9_3();
recipe.start();
}
private void start() {
try {
callSomeMethodThatMightThrow(null);
} catch (IllegalArgumentException e) {
System.err.println("There was an illegal argument exception!");
}
}
private void callSomeFunctionThatMightThrow(Object o) {
if (o == null) throw new NullPointerException("The object is null");
}
In this code example, the callSomeMethodThatMightThrow method checks to 
ensure that a valid argument was passed to it. If the argument is null, it then throws 
a NullPointerException (RuntimeException type), signaling that the caller of this 
method invoked it with the wrong parameters.
 How It Works
The throw keyword allows you to explicitly generate an exceptional condition. When 
the current thread throws an exception, it doesn’t execute anything beyond the 
throw statement and instead transfers control to the catch clause (if there are any) or 
terminates the thread.
Note When throwing an exception, be sure that you intend to do so. if an 
exception is not caught as it propagates up the stack, it terminates the executing 
thread (also known as unraveling). if your program has only one main thread, an 
uncaught exception terminates your program.
Chapter 9 exCeptions and Logging


336

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   167   168   169   170   171   172   173   174   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling