The throw statement in Java is used to explicitly throw an exception object to manually raise exceptions in the program. By throwing exceptions, programmers can clearly indicate that an error or abnormal situation occurs under certain conditions. The throw statement is often used with a try-catch block. When an exception is thrown, program control is passed to the catch block of the nearest, unhandled try block.
Usage of throw statement in Java
In Java, throw statement is used to explicitly throw a Exception object to manually raise exceptions in the program.
Syntax
<code>throw new ExceptionName();</code>
Where ExceptionName is the name of the exception class to be thrown.
Function
Throwing an exception can pass program control to the caller so that the exception can be handled at the appropriate location. By throwing exceptions, programmers can clearly indicate that an error or abnormal situation occurs under certain conditions.
When to use
Cooperation with try-catch blocks
throw statements are often used with try-catch blocks. When a throw statement throws an exception, program control is passed to the catch block of the nearest, unhandled try block.
Example
The following code example shows how to use the throw statement to throw a NullPointerException:
<code class="java">public class Main { public static void main(String[] args) { try { String str = null; if (str == null) { throw new NullPointerException("String is null"); } System.out.println(str); } catch (NullPointerException e) { System.out.println("Caught NullPointerException: " + e.getMessage()); } } }</code>
In this example, when the variable str is empty , will throw a NullPointerException. This exception is caught by the catch block and an error message is printed.
The above is the detailed content of How to use throw in java. For more information, please follow other related articles on the PHP Chinese website!