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 the *throw
* 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");
Use our Online Code Editor
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."); } }
Use our Online Code Editor
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)
Use our Online Code Editor
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 }
Use our Online Code Editor
public void readFile() throws IOException { // code that might throw IOException }
Use our Online Code Editor
public void processFile() throws IOException, ParseException { // code that might throw either IOException or ParseException }
Use our Online Code Editor
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."); } }
Use our Online Code Editor
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.
Use our Online Code Editor
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.
Example:
// Using throws public void readFile() throws IOException, SQLException { // Inside this method, you can use throw throw new IOException("File not found"); }
Use our Online Code Editor
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); } }
Use our Online Code Editor
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()); } } }
Use our Online Code Editor
In this example, we created a custom exception by extending the Exception
class, named *InvalidBookingException
.
*
Output
Booking failed: Seat number 105 is invalid!
Use our Online Code Editor
Have a great one!!!
Author: Solomon Eseme
Thank you for being a part of the community
Before you go:
Whenever you’re ready
There are 4 ways we can help you become a great backend engineer:
- The MB Platform: Join thousands of backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.
- The MB Academy: The “MB Academy” is a 6-month intensive Advanced Backend Engineering Boot Camp to produce great backend engineers.
- Join Backend Weekly: If you like posts like this, you will absolutely enjoy our exclusive weekly newsletter, sharing exclusive backend engineering resources to help you become a great Backend Engineer.
- Get Backend Jobs: Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board.
Top comments (0)