Exception handling is an essential part of Java programming, allowing developers to manage errors gracefully. While the try...catch
block catches exceptions, Java provides two additional keywords — throw
and throws
— that play a key role in throwing and propagating exceptions. Understanding how and when to use these keywords is crucial for writing robust and maintainable code.
throw
Keyword?The throw
keyword in Java is used to explicitly throw an exception. It can be used inside a method or any block of code to signal an error or exceptional condition. When an exception is thrown using throw
, the normal flow of execution is interrupted, and the control is transferred to the nearest exception handler (usually a catch
block).
throw
:
throw new ExceptionType("Exception message");
throw
public class ThrowExample {
public static void main(String[] args) {
try {
checkAge(15); // This will throw an exception
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be at least 18.");
} else {
System.out.println("Access granted.");
}
}
}
Output:
Age must be at least 18.
In this example:
checkAge
method throws an IllegalArgumentException
if the age is less than 18.throw
keyword is used to explicitly throw the exception.catch
block catches the exception and prints the error message.throws
Keyword?The throws
keyword in Java is used in a method declaration to indicate that the method might throw one or more exceptions during its execution. Unlike throw
, which is used to explicitly throw an exception, throws
is used to declare exceptions that may be thrown but are not handled within the method.
This is particularly useful for checked exceptions, which the compiler requires you to either handle or declare.
throws
:
public returnType methodName() throws ExceptionType {
// Method code
}
throws
public class ThrowsExample {
public static void main(String[] args) {
try {
methodThatThrows(); // This will throw an exception
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
static void methodThatThrows() throws Exception {
throw new Exception("This is a thrown exception.");
}
}
Output:
Caught exception: This is a thrown exception.
In this example:
methodThatThrows
declares that it can throw an exception using throws
.main
method calls methodThatThrows
and catches the exception.throw
and throws
While both throw
and throws
deal with exceptions, they serve different purposes:
Keyword | Purpose | Where it is Used | Handling Mechanism |
---|---|---|---|
throw | Used to explicitly throw an exception. | Inside methods or code blocks. | The exception is thrown immediately, interrupting normal execution. |
throws | Used to declare that a method can throw one or more exceptions. | In method signatures (declaration). | The exception is not handled inside the method but propagated to the caller. |
throw
and throws
Together
public class ThrowAndThrowsExample {
public static void main(String[] args) {
try {
methodThatThrows();
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
static void methodThatThrows() throws Exception {
throw new Exception("This is an exception thrown using throw.");
}
}
Output:
Caught exception: This is an exception thrown using throw.
In this example:
methodThatThrows
method declares that it can throw an exception using throws
.throw
keyword is used to explicitly throw an exception.throw
and throws
You can use the throw
keyword to throw custom exceptions that you define yourself. To create a custom exception, you extend the Exception
class (for checked exceptions) or the RuntimeException
class (for unchecked exceptions).
throw
and throws
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
validateAge(15); // This will throw the custom exception
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
}
}
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be at least 18.");
} else {
System.out.println("Age is valid.");
}
}
}
Output:
Age must be at least 18.
In this example:
InvalidAgeException
is created by extending the Exception
class.validateAge
method uses the throw
keyword to throw the custom exception if the age is less than 18.throws
keyword is used to declare that the method can throw the custom exception.throw
and throws
Use throw
for Immediate Exception Handling: Use the throw
keyword when you need to explicitly throw an exception, either for custom error handling or to signal that something is wrong in your method.
Use throws
for Propagating Exceptions: Use the throws
keyword when you want to declare that a method can throw an exception, allowing the calling method to handle it. This is especially useful for checked exceptions.
Always Document Exceptions: Whether using throw
or throws
, ensure that your methods clearly document the exceptions they throw. This helps other developers understand the possible error conditions.
Handle Specific Exceptions: When declaring exceptions with throws
, try to be specific about the types of exceptions your method can throw. Avoid throwing generic exceptions unless necessary.
Use Custom Exceptions Wisely: While Java provides many built-in exceptions, creating custom exceptions can help make your error handling more meaningful and specific to your application.
Copyright © 2024 Tutorialdom. Privacy Policy