What does the throws IOExeption
actually do when importing a file?
Example
public static void main(String args[]) throws IOException {
Scanner scanner = new Scanner(new File("C:\\Location"));
// more code
scanner.close();
}
What does the throws IOExeption
actually do when importing a file?
public static void main(String args[]) throws IOException {
Scanner scanner = new Scanner(new File("C:\\Location"));
// more code
scanner.close();
}
throws
indicates that a method requires a caller to either handle the exception, or allow the exception to continue being thrown up the call stack. The former requires the method that can throw the exception to be called in a try-catch block; the latter requires the calling method to include the type of exception (e.g. IOException
) in its own method signature.
In your case, main(String[] args)
includes the exception in its signature, meaning it does not plan on handling the exception but instead will pass it up the stack. Since main is the program's entry point, there is nothing else to handle the exception and the program would terminate.
In Java, the IO classes throws a checked exception called IOException
, e.g. saying "File not found". A checked exception must be handled in a try-catch block or it must be allowed to bubble up to the caller of your method by declaring that your method may cause that exception to be raised.
In your book, there's no need to handle exceptions, so simply allowing the exception to bubble up is the easiest to do. You'll learn more about this later.
The throws IOExeption
actually does not do anything when "importing" the file. Rather, it is relevant to what happens when you fail to "import" the file.
The Scanner
class throws an IOException
when the file could not be read for some reason. However, IOException
is a checked exception. This means that Java demands that you handle the exception somehow in a try/catch
block.
When you declare throws IOException
, you are telling Java that you will not handle the exception, and instead allow it to bubble up, and leave the caller of your method to handle the exception instead.
In this particular case, you are already in the main
method. So you will get a stack trace should be exception be thrown.
When you are stating that a method throws an exception you are actually saying that the code that is outside (the caller or his ancestors in the callstack) this method is the one that's gonna need to catch the exception (and maybe no one)
also, in your method, youre gonna need to use "throw
" key word.
for example, a case when the calling code IS catching the thrown execption:
class example
{
static void method() throws IOExeption
{
// in this code section you use the Scanner and from inside its code an
// an IOExeption is thrown ( using "throw IOExecption;")
}
public static void main(String args[])
{
try
{
method();
}
catch (IOExeption ioe)
{
// handle it however you want
}
}
}