throws statement for handled exceptions -- Java - 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.

Related

Java: is there a semantical difference between declaring throws Exception and declaring which exceptions are thrown? [duplicate]

This question already has answers here:
In Java, is using throws Exception instead of throwing multiple specific exceptions good practice?
(15 answers)
Closed 6 years ago.
Final edit due to this question having been marked as duplicate: this question is about the semantics of the throws declaration - the question which is this said to be a duplicate of handles different aspects of throws and none of those 15 answers there gave me the insight of the chosen answer here. Anyway - so let's keep it here as a duplicate.
In Java you have to declare a throws clause and name the exceptions that this method could throw - so the easy way is to just declare
void myMethod(...) throws Exception
or you could be more specific and for example state
void myMethod(...) throws SQLException, NamingException
in case the method may just throw these two.
I understand that it makes a difference whether in a try/catch block I
try { ... } catch (Exception exc) { ... }
or
try { ... } catch (SQLException | NamingException exc) { ... }
because the first will also catch a RuntimeException, the second won't - so this is a difference.
But is there also any difference in declaring throws Exception vs. throws SQLException, NamingException concerning the semantics of the program? The second may be more readable, but I don't see any other difference. Is there any?
But is there also any difference in declaring throws Exception vs. throws SQLException, NamingException
The difference is:
if you declare throws SQLException, NamingException the compiler assures that you have catched exactly these two exceptions. Otherwise you will get a Unhandled exception type ... error.
On the other hand, if you declare throws Exception, the compiler assures that you have catched Exception.
In the second case, you can still catch any other exception which inherits from Exception without getting a compiler error (like "Exception ... never thrown"). However, you must either catch Exception itself or add the throws Exception to the calling method to allow passing the exception further upwards. For example,
private void someMethod() throws Exception {
throw new NumberFormatException("Illegal number format");
}
If this method gets called, you can catch the NumberFormatException, but you also have to either handle the more generic Exception or declare it in the throws clause (and then handle it further up in the call hierarchy):
public void myMethod() {
try {
someMethod();
}catch(NumberFormatException nfe) {
nfe.printStackTrace();
}catch(Exception ex) {
ex.printStackTrace();
}
}
Or:
public void myMethod() throws Exception {
try {
someMethod();
}catch(NumberFormatException nfe) {
nfe.printStackTrace();
}
}
Yes, there is a difference.
When you use the throws declaration of an exception in a method, you do it so you can handle it later (using try{}catch blocks).
When you handle the exception, you might just do the e.printStackTrace(), but that's not really handling it.
Instead, imagine you want to tell your user "You didn't introduce a number, please correct this mistake" and prompt them to introduce a number. You can do this if you throw NumberFormatException in the method you use to read. But if you throw just Exception, you can't know for sure if that was the error or any other exception, and you might have unexpected behaviours because of that.
The difference between two approach lies based on Exception Handling. For example, if you like to handle all exception in same way then, you should opt for first approach. On the other hand, if you like to deal different exception in different manner, you must go for second approach
I would prefer to mention the exceptions explicitly in the function declaration after the throws keyword because then I know how I should handle these exceptions if they occur in the calling code. See the code below for better understanding..
public static void exceptionExample() throws SQlException, NamingException {
}
public static void main(String[] args) throws SQlException, NamingException {
try {
exceptionExample();
exceptionExample();
}
catch(SQlException e){
System.out.println("Sql exception has occured");
}
catch(NamingException e){
System.out.println("Naming Exception has occured");
}
}
If I would not have mentioned throws SQlException , NamingException explicitly in the function and have used only throws Exception then it implies I do not know which exception may occur. In that case in the catch() {...} block I would have used e.printStackTrace which is not really an efficient method of exception handling because user may never know what happened to the application. But here as you can see that I can inform the user that the respective exception has occurred which makes my application more user friendly.
Also Throwing Exception causes the calling code to catch the exceptions which they may not want to handle depending upon the application and all kinds of reasons.
So I would say it depends upon the wit of the programmer on how he/she wants to handle the exceptions efficiently.....

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).

what exceptions need to be thrown in java?

I have these two java codes:
class test {
public static void main(String[] args) throws IOException {
System.out.println("Before try”");
try{}
catch(Throwable d ) {}
System.out.println("done");
}
}
it will compile and print Before try and done.
class test {
public static void main(String[] args) throws IOException {
System.out.println("Before try”");
try{}
catch(java.io.IOException e ) {}
System.out.println("done");
}
}
}
this will make compilation error:
exception java.io.IOException is never thrown in body of corresponding
try statement
at javaapplication8.test.main(Try.java:63)
what is the difference between throwable exception and IOException to have these results, Is there a rule to know which exception would need to be thrown or not?
Java has a concept of checked exceptions. All Throwable are checked unless they are a sub-class of Error or RuntimeException
In the catch class, the compiler can work out whether you can throw a checked exception or not (under normal conditions), but it can't tell if you have thrown an unchecked exception so if you catch any unchecked exception, or an parent, it cannot determine whether you might throw it or not.
Your declaration of main promised that it could throw an IOException, but your code broke that promise (because you catch it yourself).

Calling a method which throws FileNotFoundException

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.

Categories