Java throw and throws
In Java, throw and throws are keywords used for exception handling.
throw is used to explicitly throw an exception from a method or block of code. The syntax for throw is as follows:
throw exception;
In this syntax, exception is the object of the exception to be thrown. The object must be an instance of a class that extends the Throwable class.
Here's an example of using throw to throw an exception:
public void divide(int num1, int num2) {
if (num2 == 0) {
throw new ArithmeticException("Cannot divide by zero.");
}
int result = num1 / num2;
System.out.println("Result: " + result);
}
In this example, the divide method checks whether the second parameter num2 is zero, and if so, throws an ArithmeticException with a message "Cannot divide by zero." Otherwise, it performs the division and prints the result.
throws is used in a method signature to declare the exception(s) that may be thrown by that method. The syntax for throws is as follows:
access-modifier return-type method-name(parameter-list) throws exception-list {
// method body
}
In this syntax, exception-list is a comma-separated list of the exceptions that the method may throw. The exceptions must be subclasses of the Throwable class.
Here's an example of using throws in a method signature:
public void readFile(String fileName) throws IOException, FileNotFoundException {
FileInputStream file = new FileInputStream(fileName);
// code to read from the file
file.close();
}
In this example, the readFile method takes a fileName parameter, opens a file with that name, reads from the file, and then closes the file. The method is declared to throw two types of exceptions: IOException and FileNotFoundException, which may occur if there is an error while opening or reading from the file.
