throw keyword in java

The 'throw' keyword is used to throw an exception explicitly.

When a throw statement is encountered and executed, execution of the further code is stopped and returned to the caller.

The throw statement takes a java.lang.Throwable as an argument.

The Throwable is propagated up the call stack until it is caught by an appropriate catch block.

Any method that throws an exception that is not a RuntimeException must also declare the exceptions it throws using a 'throws' modifier on the method declaration

Example:

1
2
3
4
5
6
7
8
9
10
11
12
 public class ReadFileExample
 {
        public method readFile(String filename) throws IOException
 {
        <statements>
 if (error)
 {
        throw new IOException("error reading file");
 }
 System.out.println("file read done");  
 }
 }
 public class ReadFileExample
 {
        public method readFile(String filename) throws IOException
 {
        <statements>
 if (error)
 {
        throw new IOException("error reading file");
 }
 System.out.println("file read done");  
 }
 }


In the above example, We are throwing IOException explicitly based on some condition inside readFile() method and hence further execution will be stopped.

So throw keyword must be used if we want to throw an exception explicitly.

When using the throw keyword to throw a checked exception from within a method, the method should do one of the following options

1) Declares the throws clause followed by the exceptions thrown by the throw statements

2) Should Catch the exceptions thrown by the throw statement.

When using the throw keyword to throw a Runtime exception from within a method, Then throws is optional

If we write catch block to handle the exception then same method will handle that exception otherwise caller can handle the exception

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on