×

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

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Get yesterdays date by no of days in Java

In this tutorial, we are going to learn how to get yesterday’s date by the no of days in Java. Using the Calendar class, one can get the current date....

1 minute read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.