difference between throw throws and throwable in Java
In Java, throw
, throws
, and Throwable
are related concepts that deal with exceptions. Let me explain each one individually:
1. throw
:
throw
is a keyword in Java used to explicitly throw an exception. When an exceptional situation arises in your code, you can use the throw
keyword to throw an exception manually.
Example:
/*
* Author: Zameer Ali Mohil
* */
public class CustomExceptionExample {
public static void main(String[] args) {
try {
int age = -1;
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
} catch (IllegalArgumentException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
In this example, an IllegalArgumentException
is thrown if the age
is negative. The throw
keyword is used to throw this exception.
2. throws
:
throws
is a keyword in Java used in method declarations to indicate that a method might throw a specific type of exception. It is used to declare exceptions but does not throw them. When you use the throws
keyword in a method signature, you are telling the caller of that method that it might encounter those exceptions and needs to handle them.
Example:
public void readFile(String fileName) throws FileNotFoundException {
// Code to read file
}
In this example, the readFile
method declares that it might throw a FileNotFoundException
. If a method has a throws
clause, calling code must handle this exception (either using a try-catch
block or declaring it in its own throws
clause).
3. Throwable
:
Throwable
is the superclass of all errors and exceptions in Java. Both Error
and Exception
classes extend Throwable
. You can catch objects of type Throwable
to catch any exception or error.
Example:
/*
* Author: Zameer Ali Mohil
* */
public class CustomExceptionExample {
public static void main(String[] args) {
try {
int result = divide(10, 0);
} catch (Throwable t) {
System.out.println("Caught Throwable: " + t.getMessage());
}
}
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed");
}
return a / b;
}
}
In this example, the divide
method throws an ArithmeticException
. The catch
block catches Throwable
, allowing it to catch both ArithmeticException
(a subclass of Throwable
) and other types of Throwable
objects.
In summary:
throw
is used to throw an exception manually.throws
is used in method declarations to indicate that the method might throw specific exceptions.Throwable
is the superclass of all errors and exceptions in Java, and you can catch it to handle any type of exception or error.