What is Throw Keyword?
The throw keyword in Java is used to explicitly throw an exception. We define the exception object that will be thrown. The Exception is accompanied by a message that describes the error. These exceptions could be due to user inputs, the server, or something else.
The throw keyword in Java allows us to throw either checked or unchecked exceptions. Its primary use is to throw a custom exception.
We may also construct our own set of circumstances and explicitly throw an exception by using the throw keyword. For example, if we divide one number by another, we can throw an ArithmeticException. We only need to establish the condition and throw the exception using the throw keyword here.
The throw keyword in Java is used to explicitly throw an exception. We define the exception object that will be thrown. The Exception is accompanied by a message that describes the error. These exceptions could be due to user inputs, the server, or something else.
The throw keyword in Java allows us to throw either checked or unchecked exceptions. Its primary use is to throw a custom exception.
We may also construct our own set of circumstances and explicitly throw an exception by using the throw keyword. For example, if we divide one number by another, we can throw an ArithmeticException. We only need to establish the condition and throw the Exception using the throw keyword here.
But how?
Let's see the syntax of the throw keyword.
throw new exception_class("error message");
Now, there are a total of three kinds of exceptions you can throw. Let's give a look at all three. Try it on online java compiler.
Throwing Unchecked Exception
If a program throws an unchecked exception, it indicates that there is an issue in the program logic.
For example, dividing a number by 0 will result in an ArithmeticException. Let's look at an example of the same.
Example
class Test {
/* This function will check */
public static void Checker(int num) {
if(num<18) {
/* ArithmeticException would be thrown */
throw new ArithmeticException("Ineligible");
}
else {
System.out.println("Eligible");
}
}
public static void main(String args[]){
/* Checking */
Checker(13);
}
}

You can also try this code with Online Java Compiler
Run CodeOutput
Exception in thread "main" java.lang.ArithmeticException: Ineligible
at Test.Checker(Main.java:8)
at Test.main(Main.java:18)
Explanation
We can see that Exception is caught, and we get output as 'Ineligible,' and then we get the error message.
Also see, Swap Function in Java
Throwing Checked Exception
Checked exceptions, in general, represent errors that are beyond the program's control. If the input file does not exist, the constructor of FileInputStream throws a FileNotFoundException. Java verifies checked exceptions throughout the compilation process. As a result, we need to define a checked exception with the throws keyword. Let's look at an example of the same.
Example
import java.io.*;
class Test {
/* Exception for File Not Found */
public static void method() throws FileNotFoundException {
/* Reading the file */
FileReader f = new FileReader("C:\\Users\\Saksham\\Desktop\\Test.txt");
BufferedReader fI = new BufferedReader(f);
/* Exception thrown */
throw new FileNotFoundException();
}
public static void main(String args[]){
/* Try and Catch */
try
{
method();
}
catch (FileNotFoundException eM)
{
eM.printStackTrace();
}
}
}
Output
java.io.FileNotFoundException: C:\Users\Saksham\Desktop\Test.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at Test.method(Main.java:8)
at Test.main(Main.java:20)
Explanation
This will throw an exception as no file will be found.
Throwing User-Defined Exception
Java allows us to construct our own exceptions, which are essentially derived classes of Exception. A custom exception, also known as a user-defined exception, is created when we create our own Exception. Let's look at an example of the same.
Example
class UserDefined extends Exception
{
public UserDefined(String str)
{
/* Calling constructor of parent Exception */
super(str);
}
}
/* Used for Exception */
class TestingClass
{
public static void main(String args[])
{
try
{
/* This is used to throw an exception */
throw new UserDefined("User Defined Exception");
}
catch (UserDefined obj)
{
System.out.println("Exception Caught");
System.out.println(obj.getMessage());
}
}
}
Output
Exception Caught
User Defined Exception
Explanation
You can see that we have created user-defined exception.
Must Read Type Conversion in Java
Advantage of Java throws Keyword
- Clarity in Error Reporting: By using the throws keyword, a method clearly communicates that it may cause certain exceptions. This transparency ensures that anyone using the method is aware of the potential risks involved.
- Enforced Error Handling: It obliges the caller to consider exception handling, thereby promoting robustness in application design by ensuring that potential errors are not ignored.
- Facilitates Error Propagation: The throws keyword allows exceptions to be propagated to higher levels of the method call stack, enabling developers to handle exceptions at an appropriate level of abstraction.
- Documentation Utility: The throws keyword serves as self-documenting code in the method signature, indicating which exceptions need attention. This is particularly useful in large projects or API design.
- Separation of Concerns: This helps maintain a clean code structure by separating error handling from the main logic, adhering to the single responsibility principle.
- Flexibility in Error Management: Developers gain the flexibility to handle exceptions at a more strategic level in the application stack rather than dealing with all issues immediately and locally.
- Promotes Consistent Handling: By declaring exceptions that can be thrown, the method ensures consistent error handling throughout the application, facilitating maintenance and scalability.
Disadvantages of Java Throws Keyword
- Potential for Cluttered Code: Requiring callers to handle exceptions can lead to cluttered code, especially if many methods in the call stack throw exceptions, complicating the program's control flow.
- Risk of Overuse: Developers may overuse the throws clause, declaring a broad array of exceptions. This can dilute the effectiveness of exception handling by burdening the caller with too many potential faults to consider.
- Delays Immediate Resolution: The throws keyword abstracts the handling of exceptions, which can sometimes delay the response to issues until higher up the call stack, possibly obscuring the source of errors.
- Increased Code Dependency: When a method declares an exception, all callers must handle or redeclare it, creating a tightly coupled code structure. This can be problematic when changes in one method’s exception handling ripple through the codebase.
- Complexity in Maintenance: Frequent changes in method exception declarations require updates to all calling methods, increasing maintenance overhead.
- Hampers Abstraction: In some cases, dealing with specific exceptions can break a method's abstraction, forcing the caller to deal with low-level details that the method could have abstracted away.
- Limits API Flexibility: Once an API method is declared with a throws keyword, removing an exception from the declaration in later versions can break backward compatibility, limiting the API’s evolution.
Frequently Asked Questions
Why is Java a platform-independent language?
Because it does not rely on a platform, Java is platform-independent. Java will now be a platform-agnostic language. Programs are compiled into byte code in Java, which is platform-agnostic. The Java Virtual System is required to run byte code on any machine.
Why is Java not a purely object-oriented language?
Because it supports primitive data types such as int, byte, long, short, and so on, Java is not a fully object-oriented language. As a result, data types such as int, float, double, and others are not object-oriented. As a result, Java is not entirely object-oriented.
What is the use of the Java util package?
It contains the classes needed to make an applet that can communicate with its applet context. It includes all of the classes needed to create user interfaces as well as paint graphics and pictures.
Why do we use import Java util.*?
It means importing all the classes and interfaces within java.util package and making them available within the current class or interface. This is shorthand wild card annotation for importing all classes within a particular package.
Conclusion
In this article, we have extensively discussed Throw in Java. We hope that this blog has helped you enhance your knowledge of Throw in Java, and if you would like to learn more, check out our articles on Library. Do upvote our blog to help other ninjas grow. Happy Coding!”
Recommended Readings: