throw
The
throw
keyword is used to explicitly throw an exception. By default, all predefined exceptions in Java are created and thrown implicitly. If we want to throw an exception manually, we use thethrow
keyword.We can throw either checked or unchecked exceptions using
throw
.When
throw
is executed, the method terminates immediately, and further code is not executed.We must create a new exception object using
throw new
ExceptionType(...)
.Only objects of classes that extend
Throwable
(or its subclasses) can be thrown.
Syntax
throw new ExceptionType("Error message");
Example
public class Mastering_backend {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
}
System.out.println("You are eligible to vote.");
}
}
In this example, we explicitly throw an IllegalArgumentException
if the age is less than 18.
Output
Exception in thread "main" java.lang.IllegalArgumentException: Age must be 18 or above
at Main.main(Main.java:5)
throws
The
throws
keyword in Java is used to declare exceptions that a method might throw.It specifies a list of exceptions that can be thrown during the execution of the method.
Syntax
returnType methodName(parameters) throws ExceptionType1, ExceptionType2 {
// method body
}
public void readFile() throws IOException {
// code that might throw IOException
}
public void processFile() throws IOException, ParseException {
// code that might throw either IOException or ParseException
}
Example
import java.io.IOException;
public class MasteringBackend {
// Method that declares it might throw an IOException
public static void readFile(String fileName) throws IOException {
if (fileName == null || fileName.isEmpty()) {
// Throwing a checked exception
throw new IOException("File name cannot be empty");
}
System.out.println("Reading file: " + fileName);
}
// Method that throws an unchecked exception
public static void validateAge(int age) {
if (age < 18) {
// Throwing an unchecked exception (no need to declare with throws)
throw new IllegalArgumentException("Age must be 18 or above");
}
System.out.println("Age is valid for access.");
}
public static void main(String[] args) {
System.out.println("== Mastering Backend ==");
// Example 1: Handling checked exception using try-catch
try {
readFile(""); // Will throw IOException
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
// Example 2: Unchecked exception (optional to handle, but can crash if not caught)
try {
validateAge(15); // Will throw IllegalArgumentException
} catch (IllegalArgumentException e) {
System.out.println("Caught IllegalArgumentException: " + e.getMessage());
}
System.out.println("Program ended successfully.");
}
}
In this example, the throws
keyword is used in the method signature to declare checked exceptions like IOException
, while unchecked exceptions like IllegalArgumentException
do not need to be declared with throws
.
Output
== Mastering Backend ==
Caught IOException: File name cannot be empty
Caught IllegalArgumentException: Age must be 18 or above
Program ended successfully.
throw
vs throws
throw
– Thethrow
keyword is used to actually throw an exception.throws
– Thethrows
keyword is used to declare a list of exceptions that a method might throw.
throw | throws |
|
|
After | After |
You write | You write |
You can only throw one exception at a time with | You can declare multiple exceptions separated by commas with |
Example:
// Using throws
public void readFile() throws IOException, SQLException {
// Inside this method, you can use throw
throw new IOException("File not found");
}
In this example, throw
is used to throw an exception (new IOException("File not found")
), and throws
is used to declare that the method may throw that exception.
User Defined exception
A user-defined exception is a custom exception created by the programmer by extending the Exception
class (for checked exceptions) or RuntimeException
class (for unchecked exceptions).
Syntax
// For a checked exception
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
// For an unchecked exception
class MyRuntimeException extends RuntimeException {
public MyRuntimeException(String message) {
super(message);
}
}
Example
// Custom exception class
class InvalidBookingException extends Exception {
public InvalidBookingException(String message) {
super(message);
}
}
public class MasteringBackend {
public static void bookSeat(int seatNumber) throws InvalidBookingException {
if (seatNumber <= 0 || seatNumber > 100) {
throw new InvalidBookingException("Seat number " + seatNumber + " is invalid!");
}
System.out.println("Seat " + seatNumber + " booked successfully.");
}
public static void main(String[] args) {
try {
bookSeat(105);
} catch (InvalidBookingException e) {
System.out.println("Booking failed: " + e.getMessage());
}
}
}
In this example, we created a custom exception by extending the Exception
class, named InvalidBookingException
.
Output
Booking failed: Seat number 105 is invalid!