public class ThrowException {
public static void main(String[] args) {
try {
foo();
}
catch(Exception e) {
if (e instanceof IOException) {
System.out.println("Completed!");
}
}
}
static void foo() {
// what should I write here to get an exception?
}
}
Hi! I just started learning exceptions and need to catch an expetion, so please can anybody provide me with a solution?
I'd be very grateful.
Thanks!
static void foo() throws IOException {
throw new IOException("your message");
}
try {
throw new IOException();
} catch(IOException e) {
System.out.println("Completed!");
}
I just started learning exceptions and need to catch an exception
To throw an exception
throw new IOException("Something happened")
To catch this exception is better not use Exception because is to much generic, instead, catch the specific exception that you know how to handle:
try {
//code that can generate exception...
}catch( IOException io ) {
// I know how to handle this...
}
If the goal is to throw the exception from the foo() method, you need to declare it as follows:
public void foo() throws IOException{
//do stuff
throw new IOException("message");
}
Then in your main:
public static void main(String[] args){
try{
foo();
} catch (IOException e){
System.out.println("Completed!");
}
}
Note that, unless foo is declared to throw an IOException, attempting to catch one will result in a compiler error. Coding it using a catch (Exception e) and an instanceof will prevent the compiler error, but is unnecessary.
throw new IOException("Test");
Please try the following code:
throw new IOException("Message");
Maybe this helps...
Note the cleaner way to catch exceptions in the example below - you don't need the e instanceof IOException.
public static void foo() throws IOException {
// some code here, when something goes wrong, you might do:
throw new IOException("error message");
}
public static void main(String[] args) {
try {
foo();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Related
Take this as example:
public class TestClass {
public static void test() throws SSLHandshakeException {
throw new SSLHandshakeException("I'm a SSL Exception");
}
public static void main(String[] args) throws SSLHandshakeException {
try {
test ();
} catch (IOException ioe) {
System.out.println("I`m handling IO exception");
}
}
}
So, I have my test method in which I'm just throwing an SSLHandshakeException which is a subtype of IOException.
The output for this is "I`m handling IO exception".
Why does this happen? I expected that my method will throw the SSLHandshakeException. Is there a rule that catch is more important than throws?
I just want to avoid using
try {
test ();
} catch (SSLHandshakeException se) {
throw se;
} catch (IOException ioe) {
System.out.println("I`m handling IO exception");
}
Because I consider it less readable
Is there a rule that catch is more important than throws?
They are two completely different things. The throws keyword is part of the method signature and is saying 'This method can throw this exception, so every caller should handle that explicitly.'
Wether or not the method actually throws that exception is irrelevant here.
As for the catch statement. SSLHandshakeException is an IOException, and so it is caught as expected.
To get the behaviour you intent you can write:
try {
test ();
} catch (SSLHandshakeException sslExc) {
throw sslExc;
} catch (IOException ioe) {
System.out.println("I`m handling IO exception that is not an SSLHandshakeException");
}
Edit: You say you find this less readable. But honestly this is just the best way. If it would behave the way you proposed than you would never be able to catch an SSLHandshakeException in a method that might also throw it? What if you want to catch it in certain conditions but throw it in others? It would just be too limiting and unintuitive.
An alternative is like so; but in my opinion this is even less readable:
try {
test ();
} catch (IOException ioe) {
if(ioe instanceof SSLHandshakeException)
throw ioe;
System.out.println("I`m handling IO exception that is not an SSLHandshakeException");
}
That's probably because you printed your custom string instead of message of exception. Try this :
public static void main(String[] args) throws SSLHandshakeException {
try {
test ();
} catch (IOException ioe) {
System.out.println("I`m handling IO exception");
System.out.println(ioe.getMessage());
}
}
SSLHandshakeException is a subclass of javax.net.ssl.SSLException wich is a subclass of java.io.IOException.
So this code :
public static void main(String[] args) throws SSLHandshakeException {
try {
test ();
} catch (IOException ioe) {
System.out.println("I`m handling IO exception");
}
}
will catch and IOException, and thus print the message "I`m handling IO exception".
In a finally block, can I tell what exception has been thrown?
I understand, that we can verify in a finally block if an exception had been thrown.
I can't envision a situation in which this would ever a sensible thing to do, but you can try something like this:
class Main {
public static void throwsException() throws Exception {
throw new Exception();
}
public static void main(String[] args) {
Exception caughtException = null;
try {
throwsException();
}
catch (Exception e) {
caughtException = e;
e.printStackTrace();
}
finally {
System.out.println(caughtException);
}
}
}
catch block and finally are 2 different scopes . The exception caught in the catch block is not visible to finally block. You can use the Alexander answer to print the exception in the finally block.
public class SampleCloseable implements AutoCloseable {
private String name;
public SampleCloseable(String name){
this.name = name;
}
#Override
public void close() throws Exception {
System.out.println("closing: " + this.name);
}
}
and the main class
public class Main{
public static void main(String args[]) {
try(SampleCloseable sampleCloseable = new SampleCloseable("test1")){
System.out.println("im in a try block");
} catch (IOException e) {
System.out.println("IOException is never thrown");
} catch (Exception e) {
} finally{
System.out.println("finally");
}
}
}
But when i removed the throws exception on close() method inside SampleCloseable
i am getting a compiler error saying that IOException is never thrown in the corresponding try block.
Because you're throwing a generic Exception. Since an IOException inherits from Exception, it might be thrown by the close() method. The caller doesn't know that it doesn't actually get thrown. It only sees the method signature that says that it could.
In fact, the close() method is free to throw any Exception of any kind. Of course that's bad practice, you should specify what specific Exceptions you're throwing.
Your confusion may that around the fact the in Java 7, the exception that is [declared to be] thrown from the close method is thrown inside the try block, so your catch block has to catch it as well.
Your close method is declared to throw an Exception, so your catch blocks have to catch that, or the method has to be declared to throw Exception.
And since IOException is a subclass of Exception, you are of course allowed to try and catch that as well, as long as your also catch/declare Exception itself.
See JLS 14.20.3.2:
The meaning of an extended try-with-resources statement [...] is given
by the following translation to a basic try-with-resources statement
(ยง14.20.3.1) nested inside a try-catch or try-finally or
try-catch-finally statement.
Your code is effectively translated to the below. Although a bit longish, it should be clear from the below what's happening in your code.
public static void main(String args[]) {
try {
Throwable primaryEx = null ;
SampleCloseable sampleCloseable = new SampleCloseable("test1")
try {
System.out.println("im in a try block");
} catch (Throwable t) {
primaryEx = t;
throw t;
} finally {
if (sampleCloseable != null) {
if (primaryEx != null) {
try {
sampleCloseable.close();
} catch (Throwable suppressedExc) {
primaryEx.addSuppressed(suppressedExc);
}
} else {
sampleCloseable.close();
}
}
} catch (IOException e) {
System.out.println("IOException is never thrown");
} catch (Exception e) {
} finally{
System.out.println("finally");
}
}
In Java, if a general exception is caught and rethrown, will outer methods still be able to catch specific exceptions?
In other words, can I do this:
try {
try {
//...
} catch (Exception e) {
//...
throw e;
}
} catch (SpecificException e) {
//...
}
re-throwing an exception does not change anything about it (it's still the same object originally thrown).
While jtahlborn answer is correct, there is one more appreciation: the compiler will see that you are throwing an exception of the generic type (even if at runtime it can be only of the specific class) and will force you to declare the generic exception in the method header.
private void test() throws FileNotFoundException {
try {
throw new FileNotFoundException("Es una exception");
} catch (IOException e) {
throw e; <-- Error because the method only throws
FileNotFoundException, not IOException
}
}
e is indeed FileNotFoundException, but as it is declared as IOException the compiler works with the broader class. What you can do is "cast" the exception.
throw (FileNotFoundException) e;
Eclipse marks the "throw e" in the inner catch as an unhandled exception, BUT it does catch the exception because when I run this it prints "It worked!". Thanks #jtahlborn. Unfortunately this means that there will still need to be an unnecessary try/catch block somewhere.
public class Tester {
public static void main(String[] args) {
try {
try {
throw new SpecificException("Test!");
} catch (Exception e) {
throw e;
}
} catch (SpecificException e) {
System.out.println("It worked!");
}
}
}
I could not compile the following code in Java, error is: misplaced construct(s). What's wrong?
public class ExceptionsTutorial {
public static void main(String[] argv) throws Exception{
try{
System.out.println("A");
try{
System.out.println("B");
throw new Exception("1");
}
catch{
System.out.println("C");
throw new Exception("2");
}
finally{
System.out.println("D");
throw new Exception("3");
}
}
finally{
System.out.println("F");
}
}
}
catch must declare what exception it catches:
catch (Exception E) {
System.out.println("C");
throw new Exception("2");
}
Read up on Java catch blocks. There is a required element that is missing in your code.
Note that Java's behavior is slightly different from that of C# or Python in this regard.