0

I am currently learning Java and found out that there are two ways to deal with checked exceptions.

  • by using try/catch() statements and enclosing the code within them

  • by using throws clause

for eg: using try/catch()

public static void openFile(String name)
{
    try
    {
        FileInputStream f = new FileInputStream(name);
    }
    catch (FileNotFoundException e)
    {
        System.out.println("File not found.");
    }
}

by using throws

public static void openFile(String name) throws FileNotFoundException
{
    FileInputStream f = new FileInputStream(name);
}

In the first case using try/catch(), the exception is handled within the method openFile(String name) itself and the calling method doesn't have to know anything about the exception that have occured inside the method.

In the second case using throws,We are passing the responsibility of dealing with the exception to the calling method instead of dealing it inside openFile(String name) method.

My question is what is the point of using throws and delegating the responsibility of dealing with the exception to the calling method,

Shouldn't it be better to deal with the exception inside method openFile(String name) using try/catch() instead of sending it up to the calling method?

How do I know which exception handling technique to use? And when?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Rahul.In
  • 61
  • 9
  • So that you can try-catch it one (or more) layer(s) above (i.e. in the method that calls the method in which the exception is thrown). – RaminS Feb 02 '19 at 01:28
  • *"How do i know which Exception handling technique to use"* - Handle the exception where you can meaningfully handle it. Sometimes that's in the method where it occurs, sometimes it isn't. There is no single universal way of dealing with all possible problems. – David Feb 02 '19 at 01:30

0 Answers0