Throws Exception Alternative to try catch

Throws Exception Alternative to try catch

Throws Exception – throws Keyword

The designer of a class knows very well, the problems that may occur while using the methods or constructors of the class, he designed. If the methods are used by another programmer, the question is how the designer informs the programmer, the possible problems that may occur while using the methods or constructors, he designed. To know this practically, let us observe some method signatures in Java API.

  1. public FileInputStream(String filename) throws FileNotFoundException
  2. public static void sleep(long milliseconds) throws InterruptedException

You observe throws exception in the above two signatures. throws is a keyword of Java used by the designer to inform the programmer about the possible problems that may arise during the use of the methods/constructors. This is known as claiming exception. Any exception that comes along throws keyword is a checked exception. When the method is used, if the exception is not handled, the program does not compile.

The first statement gives the constructor signature of FileInputStream class. The constructor is used to open the file, in read mode, passed as parameter. Now the designer warns the programmer, the file he would like to open, may not exist at all and then writing any amount of code, like file copying, is waste. This warning is informed to the programmer using throws keyword. The FileNotFoundException used with throws keyword says the file may not be found and thereby take some measures, to avoid the code failure, in such case.

The second statement illustrates the use of sleep() method. The sleep() method is used by the programmer to inactivate a running thread for the specified time, in milliseconds, passed as parameter. Internally, the inactivation is done by the underlying OS as per the advice of the JRE. Again, it depends on the thread scheduler algorithm of the OS. In this, there may be a communication gap between JRE and OS which may result in incorrect inactivation time. The warning is given using the exception, InterruptedException. This is known as claiming the exception and means that the designer claims the exception. If claimed (using throws), it must be handled, else, the program does not compile.

Let us see one example that does not compile (when exception is not handled) and compiles (when exception is handled). The following program does not compile as the checked exception thrown by the constructor is not handled.

Example on Exception not handled

The above program does not compile because the FileInputStream constructor throws a checked exception, FileNotFoundException. We know earlier, any exception that comes with throws keyword is a checked exception and should be handled, else, the program does not compile. The beauty here is, in fact, the def.txt file really exists (of course, in the same folder where the .java file exists), even then the compiler does not accept. It is the robust way of developing a language. It does not allow the programmer to take a chance.

The same previous program is just modified using exception handling mechanism with try-catch blocks. Extra code is bold-faced. Now the program happily compiles.

Exception handling with try-catch

As you can observe, the FileInputStream constructor is placed in a try block. A catch block is followed with the handler FileNotFoundException. This is the way to handle the checked exceptions. The above program, now compiles, runs and prints OK 1.

Throwing exceptions – Alternative to try-catch

The previous program is the robust way of handling the exception. OK 1 is printed even if the def.txt file does not exist. Of course, everyone accepts writing a try-catch block is laborious. But no way if the coding is required robust. There exists a way that avoids the usage of try-catch block and at the same time the program compiles (but at runtime if a problem comes, the program terminates); but this style is not robust and used by the novices learning programming or at writing sample code that can be merged later with the main code.

Example on Throws Exception used in place of try-catch block.

In the above program, instead of try-catch, throws is used in the main() method declaration. This is nothing but rethrowing the exception to the system to handle it. In this type of alternative arrangement, the program compiles and runs happily as long as problem does not arise (when def.txt file exists). If the problem arises (when def.txt file does not exist), the execution terminates simply without executing OK 1. But in earlier program, where try-catch is written, OK 1 prints even if the file does not exist. For this reason, use try-catch instead of throws in realtime programming.

Usage of throws exception in Java

throws keyword is used in two circumstances in Java.

  1. One is claiming the exception where the designer warns the programmer, the possible problems, that may arise when using the method.
  2. The second one is as an alternative to try-catch; but not robust way.

15 thoughts on “Throws Exception Alternative to try catch

  1. PRAVEEN

    Dear Sir,

    It was said that exception is a a run time error,then why exceptions are again classified into compile time exception and run time exception,in that case it should be run time exceptions only.please give explanation with suitable real time example

    Thanks
    praveen

  2. mohan

    sir, i have seen in profile of java.lang.Integer that parseInt(String) throws NumberFormatException .Then Why doesn’t javacompiler give Unreported exception as eroor?

  3. mohan

    Any exception that comes along throws keyword is a checked exception.
    can’t we have unchecked exceptions along throws keyword.plz clarify it.

    1. S. Nageswara Rao, Corporate Trainer

      In the method signature, any exception that comes after throws keyword is a checked exception. Every exception indicates a problem. Checked exception must be handled else program does not compile. If an unchecked exception also is like a checked exception, every Java line must be put in try-catch block. How much tedious it is? To avoid this only, unchecked exceptions were introduced.

Leave a Reply

Your email address will not be published. Required fields are marked *