How To Throw Exceptions In Java Using throw, throws Keywords | Throwing Exceptions
It is important to understand how to throw exceptions in Java. This will allow you to create higher quality code where errors are checked at compile time instead of runtime, and create custom exceptions that make debugging and recovery easier.

· How to throw exceptions · Throw keyword · throws keyword · Difference between throw and throws keyword · Throwing unchecked exceptions · Throwing checked exceptions · Throwing multiple exceptions · Can we throw an exception without throws · How to Rethrow an Exception
How to throw exceptions
Throwing an exception is as simple as using the “throw” statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc. Here is an example that shows how to throw an exception:
throw new Exception("Exception message");It’s limiting to use a generic exception because it makes it difficult for the calling code to catch it. It’s better to throw custom exceptions, which we will come back to in a bit.
Throw keyword
So far, you have only been catching exceptions that are thrown by the Java run-time system. However, it is possible for your program to throw an exception explicitly, using the throw statement.
The throw keyword is used to explicitly throw a single exception.
We specify the exception object which is to be thrown. The Exception has some message with it that provides the error description. These exceptions may be related to user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception.
The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.
Syntax
The general form of throw is shown here:
throw ThrowableInstance;Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. There are two ways you can obtain a Throwable object: using a parameter in a catch clause, or creating one with the new operator.
The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.
throws keyword
The throws keyword is used to declare the list of exception that a method may throw during execution of program. Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled. A method can do so by using the throws keyword.
throws is used to throw an exception object implicitly.
throws is a keyword used to indicate that this method could throw this type of exception. It is used with the method signature. More than one type of exception can be declared with method signature, they should be comma separated. The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions.
The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program. With the help of the throws keyword, we can provide information to the caller of the method about the types of exceptions the method might throw.
type method_name(parameters) throws exception_listIn the above syntax, exception_list is a comma-separated list of all the exceptions a method might throw. For example:
void testMethod() throws ArithmeticException, ArrayIndexOutOfBoundsException {
// rest of code
}In the example below, we have created a test method to demonstrate throwing an exception. The toString() method returns a textual representation of an object, but in this case the variable is null. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException.
static void testMethod() throws Exception {
String test = null;
test.toString();
}This must be handled with a try/catch block:
public class Example {
public static void main(String[] arg) {
try {
testMethod();
} catch (Exception e) {
e.printStackTrace();
}
}
}Notes :
- throws is mainly used to throw checked exception.
- If you are calling a method that declares an exception, you must either caught or declare the exception.
- We can rethrow the exception.
Difference between throw and throws keyword
The throw and throws is the concept of exception handling where the throw keyword throw the exception explicitly from a method or a block of code whereas the throws keyword is used in signature of the method.
There are many differences between throw and throws keywords. A list of differences between throw and throws are given below:
Exceptions Thrown
Java throw keyword is used throw an exception explicitly in the code, inside the function or the block of code.
Java throws keyword is used in the method signature to declare an exception which might be thrown by the function while the execution of the code.
Propagation of Exceptions
Type of exception Using throw keyword, we can only propagate unchecked exception i.e., the checked exception cannot be propagated using throw only.
Using throws keyword, we can declare both checked and unchecked exceptions. However, the throws keyword can be used to propagate checked exceptions only.
Syntax
Syntax of throw keyword includes the instance of the Exception to be thrown. Syntax wise throw keyword is followed by the instance variable.
Syntax of throws keyword includes the class names of the Exceptions to be thrown. Syntax wise throws keyword is followed by exception class names.
Point of Usage
The throw keyword is used inside a function. It is used when it is required to throw an Exception logically.
The throws keyword is used in the function signature. It is used when the function has some statements that can lead to exceptions.
Internal implementation
We are allowed to throw only one exception at a time i.e. we cannot throw multiple exceptions.
We can declare multiple exceptions using throws keyword that can be thrown by the method. For example, main() throws IOException, SQLException.
Example
throw example
// Java program to demonstrate the working
// of throw keyword in exception handling
public class GFG {
public static void main(String[] args)
{
// Use of unchecked Exception
try {
// double x=3/0;
throw new ArithmeticException();
}
catch (ArithmeticException e) {
e.printStackTrace();
}
}
}Output:
java.lang.ArithmeticException
at GFG.main(GFG.java:10)throws example
// Java program to demonstrate the working
// of throws keyword in exception handling
import java.io.*;
import java.util.*;
public class GFG {
public static void writeToFile() throws Exception
{
BufferedWriter bw = new BufferedWriter(
new FileWriter("myFile.txt"));
bw.write("Test");
bw.close();
}
public static void main(String[] args) throws Exception
{
try {
writeToFile();
}
catch (Exception e) {
e.printStackTrace();
}
}
}Output:
java.security.AccessControlException: access denied ("java.io.FilePermission" "myFile.txt" "write")
at GFG.writeToFile(GFG.java:10)Example
Here is a sample program that creates and throws an exception. The handler that catches the exception rethrows it to the outer handler.
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}This program gets two chances to deal with the same error. First, main( ) sets up an exception context and then calls demoproc( ). The demoproc( ) method then sets up another exceptionhandling context and immediately throws a new instance of NullPointerException, which is caught on the next line. The exception is then rethrown. Here is the resulting output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demoThe program also illustrates how to create one of Java’s standard exception objects. Pay close attention to this line:
throw new NullPointerException("demo");Here, new is used to construct an instance of NullPointerException. Many of Java’s builtin run-time exceptions have at least two constructors: one with no parameter and one that takes a string parameter. When the second form is used, the argument specifies a string that describes the exception. This string is displayed when the object is used as an argument to print( ) or println( ). It can also be obtained by a call to getMessage( ), which is defined by Throwable.
Throwing unchecked exceptions
An unchecked exception (also known as an runtime exception) in Java is something that has gone wrong with the program and is unrecoverable. Just because this is not a compile time exception, meaning you do not need to handle it, that does not mean you don’t need to be concerned about it.
Example
In this example, we will throw an unchecked exception if the age is below 18:
// Welcome To FavTutor
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15);
}
}Output :
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)In this example, we are explicitly throwing an ArithmeticException.
Note: ArithmeticException is an unchecked exception. It’s usually not necessary to handle unchecked exceptions.
Throwing checked exceptions
In broad terms, a checked exception (also called a logical exception) in Java is something that has gone wrong in your code and is potentially recoverable. For example, if there’s a client error when calling another API, we could retry from that exception and see if the API is back up and running the second time. A checked exception is caught at compile time so if something throws a checked exception the compiler will enforce that you handle it.
Example:
import java.io.*
class Main {
public static void findFile() throws IOException {
throw new IOException("File not found");
}
public static void main(String[] args) {
try {
findFile();
System.out.println("Rest of code in try block");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}Output
File not foundThe findFile() method throws an IOException with the message we passed to its constructor.
Note that since it is a checked exception, we must specify it in the throws clause.
The methods that call this findFile() method need to either handle this exception or specify it using throws keyword themselves.
We have handled this exception in the main() method. The flow of program execution transfers from the try block to catch block when an exception is thrown. So, the rest of the code in the try block is skipped and statements in the catch block are executed.
Throwing multiple exceptions
Here’s how we can throw multiple exceptions using the throws keyword.
import java.io.*;
class Main {
public static void findFile() throws NullPointerException, IOException, InvalidClassException {
// code that may produce NullPointerException
… … …
// code that may produce IOException
… … …
// code that may produce InvalidClassException
… … …
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e1){
System.out.println(e1.getMessage());
} catch(InvalidClassException e2){
System.out.println(e2.getMessage());
}
}
}Here, the findFile() method specifies that it can throw NullPointerException, IOException, and InvalidClassException in its throws clause.
Note that we have not handled the NullPointerException. This is because it is an unchecked exception. It is not necessary to specify it in the throws clause and handle it.
Can we throw an exception without throws
Yes, we can throw an exception manually using throw keyword without throws, if the exception is unchecked like ArithmiticExceptions …
Example
public class Main {
public int test(int n1, int n2) {
if(n2 == 0){
throw new ArithmeticException();
} else {
return n1/n2;
}
}
public static void main(String[] args) {
Main main = new Main();
try{
System.out.println(main.test(130, 0));
}catch(ArithmeticException e){
e.printStackTrace();
}
}
}Output
java.lang.ArithmeticException
at Main.test(Main.java:5)
at Main.main(Main.java:14)How to Rethrow an Exception
An exception that is caught in the try block can be thrown once again and can be handled. The try block just above the rethrow statement will catch the rethrown object. If there is no try block just above the rethrow statement then the method containing the rethrow statement handles it. To propagate an exception, the catch block can choose to rethrow the exception by using the throw statement. Note that there is no special syntax for rethrowing.
Example : Rethrowing an exception
catch(Exception e) {
System.out.println("An exception was thrown");
throw e;
}Since you already have the reference to the current exception, you can simply rethrow that reference





