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?