In Java, the throw
keyword is used to throw an exception, which indicates that an error or exceptional condition has occurred during the execution of a program.
Here's an example of how you can use the throw
keyword to throw an exception in Java:
if (value < 0) { throw new IllegalArgumentException("Value must be non-negative"); }
In this example, the throw
keyword is used to throw an IllegalArgumentException
if the value is negative. The exception is created using the new
operator and is passed a message describing the error.
It's important to note that the throw
keyword must be followed by an instance of a class that extends the Throwable
class (such as Exception
or Error
). You cannot throw a primitive type or a string using the throw
keyword.
Exceptions can be caught and handled using a try-catch
block. The try
block contains the code that may throw an exception, and the catch
block contains the code that handles the exception.
Here's an example of how you can use a try-catch
block to handle an exception thrown with the throw
keyword:
try { if (value < 0) { throw new IllegalArgumentException("Value must be non-negative"); } } catch (Exception e) { e.printStackTrace(); }