For my final in Java we have a "exceptions" part on the test with try, catch, and finally calls. When I try to put the example code into Eclipse I get errors in the catch and throw new areas. All of the errors say "Can not be resolved to type".
How do I fix this so I can learn/review what the code is supposed to be doing?
Q4 Class
public static void main(String [] args)
{
Q4Exception q1 = new Q4Exception();
try{
q1.sampleMethod();
try{
q1.sampleMethod();
}
//This catch does not throw an error
catch(RuntimeException es)
{
System.out.println("A");
}
//This catch below throws the error of cannot be resolved to a type
catch(IOException es)
{
System.out.println("B");
}
//This catch does not throw an error
catch(Exception e)
{
System.out.println("C");
}
finally{
System.out.println("D");
}
}catch(Exception e)
{
System.out.println("E");
}
finally{
System.out.println("F");
}
}
Q4Exception Class
public void sampleMethod() throws Exception
{
try{
throw new IOException("H");
}
catch(IOException err)
{
System.out.println("I");
throw new RuntimeException("J");
}
catch(Exception e)
{
System.out.println(e.toString());
System.out.println("K");
throw new Exception(“L");
}
catch(Throwable t)
{
System.out.println("M");
}
finally{
System.out.println("N");
}
}
I think it's worth mentioning that in Eclipse, Ctrl+Shif+O does the job of resolving the imports for you.
Oh, guess I could answer my own question here.
Didn't know I had to import the IOException from java.io!
Easy to just use
import java.io.*
for the imports
I discovered I was using an old version of JWT , the issue is gone after using the a newer version of JWT dependency .
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".
I need to handle Exceptions which are raised by Catch block code in Java
Example, to "handle" an Exception:
try
{
// try do something
}
catch (Exception e)
{
System.out.println("Caught Exception: " + e.getMessage());
//Do some more
}
More info see: See: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
However if you want another catch in your try catch, you can do the following:
try
{
//Do something
}
catch (IOException e)
{
System.out.println("Caught IOException: " + e.getMessage());
try
{
// Try something else
}
catch ( Exception e1 )
{
System.out.println("Caught Another exception: " + e1.getMessage());
}
}
Be careful with nested try/catch, when your try catch is getting to complex/large, consider splitting it up into its own method. For example:
try {
// do something here
}
catch(IOException e)
{
System.out.println("Caught IOException: " + e.getMessage());
foo();
}
private void foo()
{
try {
// do something here (when we have the IO exception)
}
catch(Exception e)
{
System.out.println("Caught another exception: " + e.getMessage());
}
}
Instead of cascading try/catch (like in most of the other answers), I advise you to call another method, executing the required operations. Your code will be easier to maintain by this way.
In this method, put a try/catch block to protect the code.
Example :
public int classicMethodInCaseOfException(int exampleParam) {
try {
// TODO
}
catch(Exception e)
{
methodInCaseOfException();
}
}
public int methodInCaseOfException()
{
try {
// TODO
}
catch(Exception e)
{
//TODO
}
}
Do as you would do in an usual try/catch situation :
try{
throw new Exception();
}catch(Exception e1){
try{
throw new Exception();
}catch(Exception e2){
//do something
}
}
You can add new try catch block in your main catch block.
try
{
int b=10/0;
}catch(ArithmeticException e)
{
System.out.println("ArithmeticException occurred");
try
{
int c=20/0;
}catch(ArithmeticException e1)
{
System.out.println("Another ArithmeticException occurred");
}
}
I think the most clean way is to create method which is catching the exceptions occurs in its body. However it can be very dependent to the situation and type of code you are dealing with.
One example of what you are asking about is closing a Stream which is opened in a try-catch-finally block. For example:
package a;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Main {
public static void main(String[] args) {
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream("temp.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
//TODO: Log the exception and handle it,
// for example show a message to the user
} finally {
//out.close(); //Second level exception is
// occurring in closing the
// Stream. Move it to a new method:
closeOutPutStreamResource(out);
}
}
private static void closeOutPutStreamResource(OutputStream out){
try {
out.close();
} catch (IOException e) {
// TODO: log the exception and ignore
// if it's not important
// OR
// Throw an instance of RuntimeException
// or one of it's subclasses
// which doesn't make you to catch it
// using a try-catch block (unchecked)
throw new CloseOutPutStreamException(e);
}
}
}
class CloseOutPutStreamException extends RuntimeException{
public CloseOutPutStreamException() {
super();
}
public CloseOutPutStreamException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public CloseOutPutStreamException(String message, Throwable cause) {
super(message, cause);
}
public CloseOutPutStreamException(String message) {
super(message);
}
public CloseOutPutStreamException(Throwable cause) {
super(cause);
}
}
Here I illustrated a situation which the second level exception is occurring in the finally block, but the same can apply for the exceptions occur in the catch block.
In my point of view writing methods such as closeOutPutStreamResource can be useful because they are packaging a boiler plate code for handling very common exceptions and they are making your codes more elegant.
Also it would be your choice to catch and log the exception in closeOutPutStreamResource or to throw it to other layers of your program. But it would be more elegant to wrap this unimportant checked exceptions into RuntimeException without a need for catching.
Hope this would be helpful.
You can use try catch block any where in methods or in block, so you can write try catch in catch block as well.
try {
// master try
}catch(Exception e){
// master catch
try {
// child try in master catch
}catch(Exception e1){
// child catch in master catch
}
}//master catch
It's not necessary to have a nested try-catch block when catch block throws Exception as all answers here suggest. You can enclose the caller method with try-catch to handle that Exception.
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());
}
}
java.net.ConnectException extends java.net.SocketException
If I do the following, will it cater for both exceptions? ie if I catch a "parent" exception using instanceof, does that include any subclassed exceptions?
catch (Exception e)
{
if (e instanceof java.net.SocketException)
{
System.out.println("You've caught a SocketException, OR a ConnectException");
}
}
(and for the record, yes I know catching plain Exceptions is bad, just using it for this example ;) )
Exceptions are regular classes, so instanceof works fine for them.
But you don't need such a thing. The following achieves the same result:
try {
throw new ConnectException();
} catch (SocketException e) {
System.out.println("You've caught a SocketException, OR a ConnectException");
}
Yes, it will cater for both. Because ConnectionException IS A SocketException, it also is an instance of it.
Bozho already has given the right answer. I don't know your particular usecase, but you'd rather catch different exceptions:
try {
...
}
catch (SocketException ex) {
System.out.println("You've caught a SocketException, OR a ConnectException");
}
catch (Exception ex) {
...
}
I know that it's now a good way but if you want to do custom action in a many places in code you can do something like this:
public class ImageIOExecption extends Exception {
Exception ex;
public ImageIOExecption(Exception ex) {
this.ex = ex;
doCatch();
}
private void doCatch() {
System.err.println(ex.getClass());
if (ex instanceof java.net.SocketTimeoutException) {
System.out.println("You've caught a SocketTimeoutException, OR a ConnectException");
}
if (ex instanceof java.net.SocketException) {
System.out.println("You've caught a SocketException, OR a ConnectException");
}
}
}
public BufferedImage getBufferedImage() {
try {
BufferedImage srcImage = ImageIO.read(is);
is.close();
return srcImage;
} catch (Exception ex) {
new ImageIOExecption(ex);
}
return null;
}
Yes, that is how instanceof works. For exceptions it is more common to use something like this if you care about different exceptions. It works because the JVM will work down the list of catch statements in order and execute the first one that matches.
catch(ConnectException e)
{
//got ConnectException
}
catch(SocketException e)
{
/got a SocketException
}
catch(Exception e)
{
//got some other exception
}
Or below if you dont care about the difference between Connection and Socket Exception
catch(SocketException e)
{
//got a SocketException or a subclass e.g. ConnectionException
}
catch(Exception e)
{
//got another type of exception
}
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.