throw and throws in exception handling

 

🔹 throw Keyword in Java

The throw keyword is used to explicitly throw an exception from a method or block of code.

✅ Syntax:

throw new ExceptionType("Error message");

✅ Key Points:

  • You can throw only one exception at a time using throw.

  • You must throw an object of type Throwable (or subclass like Exception, RuntimeException, etc.).

  • Common for manual exception generation.


📘 Example 1: Using throw with unchecked exception


public class ThrowExample { public static void main(String[] args) { int age = 15; if (age < 18) { throw new ArithmeticException("You must be 18 or older."); } System.out.println("Access granted."); } }

🔸 Output:

Exception in thread "main" java.lang.ArithmeticException: You must be 18 or older.

🔹 throws Keyword in Java

The throws keyword is used in method declarations to indicate that a method may throw one or more exceptions.

✅ Syntax:


returnType methodName() throws ExceptionType1, ExceptionType2 { // method code }

✅ Key Points:

  • Used with checked exceptions.

  • Propagates the responsibility to handle the exception to the caller.


📘 Example 2: Using throws with checked exception


import java.io.*; public class ThrowsExample { public static void main(String[] args) throws IOException { readFile(); } static void readFile() throws IOException { FileReader fr = new FileReader("file.txt"); // file might not exist BufferedReader br = new BufferedReader(fr); System.out.println(br.readLine()); } }

🔸 Output (if file not found):


Exception in thread "main" java.io.FileNotFoundException: file.txt (No such file or directory)

If you don't handle or declare the checked exception, the compiler will throw an error.


✅ Differences between throw and throws

Featurethrowthrows
PurposeTo explicitly throw an exceptionTo declare exceptions that a method might throw
Used inInside method bodyIn method signature
Can throwOne exception at a timeMultiple exceptions (comma separated)
Examplethrow new IOException();void read() throws IOException

📘 Example 3: Combining throw and throws


public class ThrowThrowsExample { public static void main(String[] args) { try { checkMarks(30); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } } static void checkMarks(int marks) throws Exception { if (marks < 40) { throw new Exception("Marks too low to pass."); } System.out.println("You passed!"); } }

🔸 Output:


Exception: Marks too low to pass.

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism