what exceptions need to be thrown in java? - 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).

Related

Exception doesn't need to be thrown to be caught, but IOException does

Why does the following code compile fine, but the method being called does not need to throw Exception? Isn't Exception a checked exception and not an unchecked exception? Please clarify.
class App {
public static void main(String[] args) {
try {
amethod();
System.out.println("try ");
} catch (Exception e) {
System.out.print("catch ");
} finally {
System.out.print("finally ");
}
System.out.print("out ");
}
public static void amethod() { }
}
If I want to use a try catch with IOexception (a checked exception), the method being called needs to throw IOException. I get this.
import java.io.IOException;
class App {
public static void main(String[] args) {
try {
amethod();
System.out.println("try ");
} catch (IOException e) {
System.out.print("catch ");
} finally {
System.out.print("finally ");
}
System.out.print("out ");
}
public static void amethod() throws IOException { }
}
Isn't 'Exception' a checked exception and not an unchecked exception?
Yes, it is.
But even if we know the method doesn't throw Exception itself, the code catch(Exception e){ could still execute. The code in the try block could still throw something that inherits from Exception. That includes RuntimeException and its subclasses, which are unchecked.
catch(IOException e){, on the other hand, can only catch checked exceptions. (Java doesn't allow multiple inheritance, so anything that's a subclass of IOException can't possibly be a subclass of RuntimeException.) The compiler can fairly easily figure out that none of the code in the try block can possibly throw an IOException (since any method throwing a checked exception must explicitly say so) which allows it to flag the code.
Normally there would be a compiler error for having a try block that never throws a checked exception that you have a catch block for, but the behavior you're observing comes from the fact that the Java Language Specification treats Exception specially in this circumstance. According to §11.2.3:
It is a compile-time error if a catch clause can catch checked exception class E1 and it is not the case that the try block corresponding to the catch clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 is Exception or a superclass of Exception.
This is reasonable because Exception (and its superclass Throwable) can be used to catch exceptions that extend RuntimeException also. Since runtime exceptions are always possible, the compiler always allows Exception to appear in a catch clause regardless of the presence of checked exceptions.

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.

Is ValidationException a runtime exception or not?

Can anyone please give me information about it. I cant really uderstand the type of this Exception.
Thank you
public class ValidationException extends Exception{
public ValidationException(){
super("There was a problem when validating data");
}
public ValidationException(String message){
super(message);
}
public ValidationException(String message, Throwable throwable){
super(message, throwable);
}
public ValidationException(Throwable throwable){
super(throwable);
}
}
It is a "runtime exception" in the (fatuous) sense that it is an exception that occurs at runtime. But that is true for all Java exceptions ... apart from bugs in the compiler, etcetera.
It is not a subclass of RuntimeException. You have declared it as a subclass of Exception and Exception is not a subclass of RuntimeException. (In fact, the reverse is true: RuntimeException is a subclass of Exception!)
It is a checked exception because it is not a subclass of RuntimeException (or Error).
Since it is a checked exception, the Java rules about checked exceptions apply. For example, any method that throws or propagates1 your exception must declare that it throws this exception, or an exception that is a superclass of this exception.
1 - Technically, the JLS describes this as an abnormal termination of the method body with this exception as the abnormal termination reason.
The main difference between Exception, and RuntimeException is that we need to wrap a Exception in a try/catch block. A RuntimeException does not need to be caught, but it is just as lethal as an Exception.
public class Main{
public static void main(String[] args) {
Thread.currentThread().setUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler(){
#Override
public void uncaughtException(Thread t, Throwable e){
System.out.println("Uncaught Exception " + e);
}
});
try{
throwException();
}catch(Exception e){
System.out.println("Caught Exception " + e);
}
try{
throwRuntimeException();
}catch(Exception e){
System.out.println("Caught RuntimeException " + e);
}
//unchecked, no need to wrap int try/catch
throwRuntimeException();
}
public static void throwException() throws Exception {
throw new Exception();
}
public static void throwRuntimeException() {
throw new RuntimeException();
}
}
Take this example above. The output is this:
Caught Exception java.lang.Exception
Caught RuntimeException java.lang.RuntimeException
Uncaught Exception java.lang.RuntimeException
As you can tell, the call to throwRuntimeException() gets thrown, and since there is no try/catch block it has no idea how to handle it. This crashes the thread and since there is an UncaughtExceptionHandler it gets called.
Then there is also Error which I won't go into since I don't know much about it besides that JVM throws it. OutOfMemoryError is an example.

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.

Java exception handling

I have the following code. In that fn2 is actually throwing an exception and it is caught in the function itself. In the function fn1 the compiler is complaining about unhandled exception since fn2 is declared to be throwing an Exception.
Why it is so? Since the exception is caught inside fn2 it shouldn't be complaining right?
Please explain the behavior.
public class ExepTest {
/**
* #param args
*/
public static void main(String[] args) {
ExepTest exT = new ExepTest();
exT.fn1();
}
public void fn1(){
fn2();//compilation error
}
public void fn2() throws Exception{
try{
throw new Exception();
}
catch(Exception ex){
System.out.println("Exception caught");
}
}
}
Compiler doesn't/can't know that at runtime no exception will be throwed by fn2() since it's declared that it may throw an Exception, that's why you got an error.
Remove the throws Exception from fn2() signature
The signature of the method fn2 is all that matters here. In that signature you declare that fn2 may throw an Exception. Any code that calls a method that may throw an Exception must handle the eexception.
public void fn2() throws Exception. The compiler see that declaration and expect each caller to fn2 to handle / rethrow the exception.
Exception is thrown BY fn2, not inside it. So it will be actually thrown where it is called. Since it is called in fn1, it is behaving like this.
You need to surround the call to fn2() in a try-catch block, or declare that fn1 also throws an exception.
public void fn1(){
fn2();//compilation error
}
public void fn2() throws Exception{
try{
throw new Exception();
}
catch(Exception ex){
System.out.println("Exception caught");
}
}
}
Here compiler will not recognize that you have handled exception or not. It just assumes that fn2 throws exception as you have declared to be and that's why it's showing error.
To run program either remove throws Exception from fn2 or write throws Exception in fn1 or handle it in try..catch in fn1.

Categories