1. What is throw in java?
- throw is a keyword in java.
- When an exceptional or unintended situation occurs in a our Java Application program, an exception object is created, to catch this abnormal flow.
throw
keyword is used to explicitly throw an exception.- This exception object can then be thrown using the
throw
keyword java.
- This exception object can then be thrown using the
- throw is used to throw exception, from method or executable block.
- When the
throw
statement is executed, an exception is thrown, and the normal flow of the program is disrupted. - This exception is then caught and handled by an appropriate exception-handling mechanism, such as a
try-catch
block.
Example: How to use throw keyword in java?
We will discuss an example of throw keyword, In the following example, the throw
statement is used to throw a IllegalArgumentException , when the salary or age of person is negative (less than zero). The block then catches the exception and handles it by printing a message.
public class Person { private String name; private int age; private double salary; public Person(String name, int age, double salary) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } if (salary < 0) { throw new IllegalArgumentException("Salary cannot be negative"); } this.name = name; this.age = age; this.salary = salary; } public static void main(String[] args) { try { // Creating a person with negative age to trigger an exception Person person1 = new Person("John", -25, 50000.0); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } try { // Creating a person with negative salary to trigger an exception Person person2 = new Person("Alice", 30, -60000.0); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } } }
Person class has a constructor that takes a name, age, and salary as parameters. Before setting the values, it checks whether the age and salary are negative.
If either of them is negative, it throws an IllegalArgumentException with an appropriate error message. We are catching the exceptions in the main method, so that we can take appropriate corrective actions.
2. What is throws?
- throws is keyword in java.
throws
is used in the method signature to declare that the method may throw certain types of exceptions.
public static void printPage() throws IOException
- throws signifies, the kind of exception, the method can throw.
- When a method uses the
throws
, it signify that the method does not handle the exceptions itself but expects the calling method to handle it.
Example: How to use throws in java?
import java.io.IOException; public class DemoThrows { public static void printPage() throws IOException { throw new IOException("Simulated IOException in printPage method"); } public static void main(String[] args) { try { printPage(); } catch (IOException e) { System.out.println("An IOException occurred: " + e.getMessage()); } } }
The printPage
method is declared to throw an IOException
, and the main
method calls this method within a try-catch block to handle any IOException
thrown my printPage
method.
3. What is Throwable in java?
Throwable
is the root class for all exceptions and errors.- Both exceptions and errors in Java extend from the
Throwable
class, making it the superclass of all exception classes.
- Both exceptions and errors in Java extend from the
- All kind of exceptions and error are kind of throwable type.
- The
Throwable
class has two main subclasses:Exception
andError
.
- The
The class hierarchy of Throwable is as follows:
Exception class:
- Exceptions are abnormal conditions that occur during the execution of a program.
- They are divided into two categories:
- Checked exceptions
- Checked exceptions must be either caught by a try-catch block or declared in the method’s
throws
clause (IOException is an example of Checked Exception).
- Checked exceptions must be either caught by a try-catch block or declared in the method’s
- Unchecked exceptions.
- Unchecked exceptions (often subclasses of
RuntimeException
) do not require explicit handling or declaration.
- Unchecked exceptions (often subclasses of
- Checked exceptions
Error:
- Errors are exceptional conditions that typically indicate a serious problem in the application.
- Unlike exceptions, errors are not meant to be caught by normal program code.
- Errors are usually signify unrecoverable issues
- Examples of Errors are out-of-memory errors or internal system failures.
Program: How to use Throwable Exceptions
- The
processFile
method simulates reading from a file. It throws aFileNotFoundException
- If the specified file is not found and catches exceptions that might occur.
- In the
main
method,- We are calling process a file with valid or invalid path. If a
FileNotFoundException
occurs, - If any unexpected
Throwable
(including potentialError
instances) occurs, it is caught separately for using Throwable keyword.
- We are calling process a file with valid or invalid path. If a
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class FileProcessor { public static void processFile(String filePath) throws FileNotFoundException { File file = new File(filePath); try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } scanner.close(); } catch (FileNotFoundException e) { System.out.println("File not found: " + e.getMessage()); throw e; } catch (Exception e) { System.out.println("An unexpected exception occurred: " + e.getMessage()); } } public static void main(String[] args) { String filePath = "nonexistentfile.txt"; try { processFile(filePath); } catch (FileNotFoundException e) { System.out.println("Error: " + e.getMessage()); } catch (Throwable t) { System.out.println("Unexpected error: " + t.getMessage()); } } }
Summary – throw, throws & Throwable in java
- throw & throws are keyword in java.
- Throwable is super class of all exceptions ( & errors).
- throws signifies, the kind of exception, the method can throw
- throw is used to throw exception, from method or executable block.