×

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”
keywords in Java programming language.
The throw keyword tells Java you want another part of the code to deal with
the exception, so it’s used to throw an exception explicitly, but throws is used
to declare exception in method signature.
You can declare one or more exception with throws like:

public Date getDate() throws RuntimeException, DateTimeParseException.

You can throw just one exception with throw like:

throw new RuntimeException();

So difference between throw and throws is that:
Throw means an exception is actually being thrown, and throws
indicate that the method has the potential to throw that exception. The
following example uses both:

public User getUserData(int id) throws SQLException{
throw new UnsupportedOperationException();
}

The first line declares that the method might or might not throw a
SQlException. Since this is a checked exception, the caller need to handle or
declare it.
The second line does throw an UnsupportedOperationException. Since this is
a runtime exception, it does not need to be declared on the first line and you
should catch this exception and handle it.

Another difference between throw and throws is that:
throws is followed by Exception class like: “IoException”.
But throw is followed by an instance of Exception class like:

throw new IOException("IOException is fired.");

Throw Example:

public void writeInFile () {
try {
throw new IOException("File not found");
} catch(Exception e ){
System.out.println(“The error is: ” + e.getMessage());
}
}

Throws Example:

public void writeInFile () throws IoException, RuntimeException, NullPointerException{
try {
// Error occurred here cause by Null pointer exception
} catch(Exception e ){
System.out.println(“The error is: ” + e.getMessage());
throw new NullPointerException();
}
}

As you read in previous examples, throws just declare exceptions that your method may or may not be thrown, if there is no error then your code run successfully without throwing any exceptions declared after throws keyword.
But when you write “throw new MyException(“Something error.”); ” then you explicitly throw new instance of the declared exception.

Very important thing is “Exception propagation”:

When method called “m1” called method “m2” which called “m3” then we call that is call stack. When something wrong occurred in “m3” it throws and exception, this exception will propagate from “m3” to “m2” to “m1” to … unless one of them catch this exception in catch clause.

Throwing a Second Exception

Most of us limit himself to one try statement in his code. However a catch or finally block can have any valid code in it including try statement.
Example: The following code tries to read a file:

private FileReader readFile() throws IOException{
// your code here.
}
private testReadFile () {
FileReader fReader = null;
try {
fReader = readFile()
} catch (IOException e ) {
try {
if (fReader != null){
fReader.close();
}
} catch (Exception e ){
// do something
}
}
}

Related Topics

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

Method Overloading In Java

If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method...

2 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.

Java Integer equals() method

The equals() method of Integer class compares the given object to the specified object. Syntax public boolean equals(Object obj) Parameters The parameter ‘obj’ represents the object to be compared with. Overrides The equals() method overrides equals...

1 minute read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.