Calling a method which throws FileNotFoundException - java

I'm pretty sure this is an easy one but I could not find a straight forward answer. How do I call a method with a throws FileNotFoundException?
Here's my method:
private static void fallingBlocks() throws FileNotFoundException

You call it, and either declare that your method throws it too, or catch it:
public void foo() throws FileNotFoundException // Or e.g. throws IOException
{
// Do stuff
fallingBlocks();
}
Or:
public void foo()
{
// Do stuff
try
{
fallingBlocks();
}
catch (FileNotFoundException e)
{
// Handle the exception
}
}
See section 11.2 of the Java Language Specification or the Java Tutorial on Exceptions for more details.

You just call it as you would call any other method, and make sure that you either
catch and handle FileNotFoundException in the calling method;
make sure that the calling method has FileNotFoundException or a superclass thereof on its throws list.

You simply catch the Exception or rethrow it. Read about exceptions.

Not sure if I get your question, just call the method:
try {
fallingBlocks();
} catch (FileNotFoundException e) {
/* handle */
}

Isn't it like calling a normal method. The only difference is you have to handle the exception either by surrounding it in try..catch or by throwing the same exception from the caller method.
try {
// --- some logic
fallingBlocks();
// --- some other logic
} catch (FileNotFoundException e) {
// --- exception handling
}
or
public void myMethod() throws FileNotFoundException {
// --- some logic
fallingBlocks();
// --- some other logic
}

You call it like any other method too. However the method might fail. In this case the method throws the exception. This exception should be caught with a try-catch statement as it interrupts your program flow.

Related

What is the meaning of this statement from a blog saying a function has to declare Throwable at method signature to catch it?

I am trying to understand exception handling in Java and i keep running into variations of the below mentioned confusing statement in several articles -
There are several reasons why catching instance of java.lang.Throwable is bad idea, because in order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable.
This is from http://javarevisited.blogspot.com/2014/02/why-catching-throwable-or-error-is-bad.html#ixzz4hQPkFktf
However, this code compiles -
class CatchThrowable
{
void function()
{
try
{
throw new Throwable();
}
catch (Throwable t)
{
}
}
public static void main(String[] args)
{
try
{
}
catch (Throwable t)
{
}
}
}
Both main and function are able to catch Throwable without declaring that they throw it. My understanding is that the throws keyword is used to declare the checked exceptions which a function throws, not those which it catches. Please clarify the quoted statement.
The statement:
order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable.
is basically wrong.
You just have to understand the following. There is a exception Hierarchy
A method can throw all types of exception, it just depends on your needs which one you catch and which one not.
It is also not a good idea to catch Error (which includes that you should also not catch Throwable) because there are some severe JMV-VirtualMachineError's like OutOfMemoryError which you usually not should catch.
But this has nothing to do which the fact, what a method declares in its throws part.

what is the major difference between the given 2 programs having TRY & CATCH and THROWS exception in JAVA [duplicate]

So I thought I had a good basic understanding of exception-handling in Java, but I was recently reading some code that gave me some confusion and doubts. My main doubt that I want to address here is when should a person use throws in a Java method declaration like the following:
public void method() throws SomeException
{
// method body here
}
From reading some similar posts I gather that throws is used as a sort of declaration that SomeException could be thrown during the execution of the method.
My confusion comes from some code that looked like this:
public void method() throws IOException
{
try
{
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
Is there any reason that you would want to use a throws in this example? It seems that if you are just doing basic exception-handling of something like an IOException that you would simply need the try/catch block and that's it.
If you are catching an exception type, you do not need to throw it, unless you are going to rethrow it. In the example you post, the developer should have done one or another, not both.
Typically, if you are not going to do anything with the exception, you should not catch it.
The most dangerous thing you can do is catch an exception and not do anything with it.
A good discussion of when it is appropriate to throw exceptions is here
When to throw an exception?
You only need to include a throws clause on a method if the method throws a checked exception. If the method throws a runtime exception then there is no need to do so.
See here for some background on checked vs unchecked exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
If the method catches the exception and deals with it internally (as in your second example) then there is no need to include a throws clause.
The code that you looked at is not ideal. You should either:
Catch the exception and handle it;
in which case the throws is
unnecesary.
Remove the try/catch; in which case
the Exception will be handled by a
calling method.
Catch the exception, possibly
perform some action and then rethrow
the exception (not just the message)
You're correct, in that example the throws is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.
The code you posted is wrong, it should throw an Exception if is catching a specific exception in order to handler IOException but throwing not catched exceptions.
Something like:
public void method() throws Exception {
try {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
or
public void method() {
try {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
} catch(IOException e) {
System.out.println("Catching IOException");
System.out.println(e.getMessage());
} catch(Exception e) {
System.out.println("Catching any other Exceptions like NullPontException, FileNotFoundExceptioon, etc.");
System.out.println(e.getMessage());
}
}
In the example you gave, the method will never throw an IOException, therefore the declaration is wrong (but valid). My guess is that the original method threw the IOException, but it was then updated to handle the exception within but the declaration was not changed.
This is not an answer, but a comment, but I could not write a comment with a formatted code, so here is the comment.
Lets say there is
public static void main(String[] args) {
try {
// do nothing or throw a RuntimeException
throw new RuntimeException("test");
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
The output is
test
Exception in thread "main" java.lang.RuntimeException: test
at MyClass.main(MyClass.java:10)
That method does not declare any "throws" Exceptions, but throws them!
The trick is that the thrown exceptions are RuntimeExceptions (unchecked) that are not needed to be declared on the method.
It is a bit misleading for the reader of the method, since all she sees is a "throw e;" statement but no declaration of the throws exception
Now, if we have
public static void main(String[] args) throws Exception {
try {
throw new Exception("test");
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
We MUST declare the "throws" exceptions in the method otherwise we get a compiler error.

Do we need to throw the same exception in catch block which is already mentioned in method signature using throws declaration

I have a method in my Java App which throws SQLException. Is it necessary to throw the SQLException in the catch block so that the exception is thrown to the calling method where the exception is handled?
public void insert(Connection conn) throws SQLException
{
try {
// my code
} catch (SQLException s) {
throw s;
}
}
If you want to handle the exception yourself and then pass it to the calling method, then yes, you will need to re-throw it:
public void insert(Connection conn) throws SQLException {
try {
// Your code.
} catch (SQLException s) {
// Handle s.
throw s;
}
}
If you don't need to do anything with the exception and just want to pass it to the calling method then you can just omit the try-catch and if an exception is thrown the calling method will receive it:
public void insert(Connection conn) throws SQLException {
// Your code.
}
The error occur because you place your code inside a 'try-catch' block, if any exception will happen the catch block handle with it. not send to the calling method.
You can use the below function to thrown the exception to the calling method
public void insert(Connection conn) throws SQLException {
//code.
}
If you declare exception in throws clause of the method, then you can:
1) throw exception of declared type.
2) throw exception of subtype of declared type.
3) swallow the exception. (Not recommended as you have declared it in signature)
4) throw any other runtime exception.
Now coming to your example, It would be good to re-throw the exception so that the caller method knows that something wrong happened and take appropriate action (e.g. if a transaction is running on the Connection object then roll-back the transaction).

throws statement for handled exceptions -- Java

Suppose the following code:
public static void somMethod() throws IOException {
try {
// some code that can throw an IOException and no other checked exceptions
} catch (IOException e) {
// some stuff here -- no exception thrown in this block
}
}
someMethod throws an IOException, and no other checked exception,
and handles that exception itself.
What exactly
throws IOException
in its declaration is bringing in?
From what I know, it is making it possible for the methods
calling someMethod() handle that IOException themselves.
is anything else happening here?
If the catch block doesn't throw IOException, the throws IOException part in the method signature is not necessary. And also, every time the someMethod() is invoked, there has to be provided a catch block for a possible exception that actually never occurs.

Throwing Java Exceptions

When a method throws and exception, do we need to have a try block inside the method?
For example,
public void foo() throws SomeException{
try{
// content of method
}
}
Is the try block required? Or, is the method able to throw a SomeException without it :
public void foo() throws SomeException{
// content of method
}
This is the case when we are not explicitly throwing a SomeException with throw.
If SomeException is a checked exception you have to either
Use a try{}catch block or
Declare that your method throws it.
You do not have to do both, either example you show in your question works just fine.
The difference is that with the try clause you handle the SomeException yourself, whereas by declaring that your own method throws it you delegate the responsability of handling the SomeException to the calling method.
When a method throws an exception it passes responsibility to handle exception to its caller.
So you don't need to handle exception if you throw it in your signature. Like as follows.
public void foo(){
try{
// content of method
}
}
but if you write it this way.
public void foo() throws SomeException{
}
you will call your method like as follows.
try{
foo();
}
You don't need a try block.
public void foo() throws SomeException {
// do some stuff
// you decide to throw the exception by yourself:
if (throwAnException) throw new SomeException();
// or you call a method that throws SomeExpection:
methodThatCanThrowSomeException();
// do more stuff
}
As long as you declare it in your signature, you're prefectly fine. The caller of your method has to handle the exception, not you. So a caller might do:
try {
foo();
} catch (SomeException e) {
// handle exception
}
Or he might pass it further along by himself.
The most problematic case you'll regularly encounter is calling a method that declares a checked exception. In the great majority of real-life cases it is not appropriate to handle that exception at the spot, but let it propagate upwards. Unfortunately, Java makes you redeclare this same exception all the way up, which creates clutter, exposes implementation details, and often also breaks the contracts of existing methods.
In such a case the way to proceed is to wrap and rethrow:
catch (RuntimeException e) {throw e;} catch (Exception e) {throw new RuntimeException(e);}
1. If the method that we are calling from a program throws an Exception, then we need to usetry/catch around the method invocation.
2. Suppose we are writing a method that throws an exception, then we need to throw new Exception object from withing the method.
3. An exception is an object of type Exception. We have Checked Exception, and Unchecked Exception (Runtime Exception).
you don't essentially need to have a try block in it
public void foo() throws SomeException {
// do some stuff
// you decide to throw the exception by yourself:
if (throwAnException) throw new SomeException();
// or you call a method that throws SomeExpection:
methodThatCanThrowSomeException();
// do more stuff
}

Categories