This is what i have right now, this method open's a connection with http url,
public static void setCameraList(String list) {
URL calculator;
try {
String url = "http://example.com/index.php?cameraList=" +URLEncoder.encode(list, "ISO-8859-1");
calculator = new URL(url);
URLConnection calcConnection = calculator.openConnection();
BufferedReader streamReader = new BufferedReader(new InputStreamReader(calcConnection.getInputStream()));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
This work's fine, but sometimes when url is unreachable or return's some error code this method seem's to crash full app.
What i am curious about is, Why this method fails to catch Exception ?
Also, If i add this :
catch(Throwable th){
}
Will this method catch every possible error/exception related to what operation's i perform inside it ?
I'm not a Java expert, but you should consider that there is a difference between exception and error.
Did you have a look here?
May you post the stacktrace?
Thank you
If you add this : catch(Throwable th){ } every single exception your method throws will be catch. In order to resolve your problem properly, you must pay atention about what type of exception is thrown when the problem you are describing happens!
Related
I have asked a question in aptitude test that a new try catch block can be inside a catch block or not?
For example
try {
} catch (Exception e) {
try {
} catch (Exception e) {
}
}
Is this valid in Java?
Yes it is possible tried following example with java8. it is working fine.
public static void main(String []args){
try{
System.out.println("try1");
throw new Exception("Exception1");
}catch(Exception e){
System.out.println("catch1");
try{
System.out.println("try2");
throw new Exception("Exception2");
}catch(Exception e1){
System.out.println("catch2");
}
}
}
Yes (given that you use upper/lower case correctly: try, catch, Exception)
Yes, It is possible because if any exception is occurs in try then it's catch and we want to add some logic or next implementation in catch block then we can.for example if we write code for get data in outer try block and getting any exception and we need add some logic like file releated or thread releated then we add and use try catch block in outer catch.
I am creating a kind of messenger program, where clients communicate with the server etc.
The problem I have stumbled upon is when trying to create the ObjectInputStream and the ObjectOutputStream. Here is the method that instantiated the object streams:
private void initializeStreams() {
try {
input = new ObjectInputStream(socket.getInputStream());
if (input != null) {
System.out.println("ObjectInputStream successfully initiated");
} else {
System.out.println("ObjectInputStream is null but did not return an exception when being instantiated");
}
} catch (IOException ioe) {
System.out.println("Could not initialize ObjectInputStream: " + ioe.getMessage());
}
try {
output = new ObjectOutputStream(socket.getOutputStream());
if (output != null) {
System.out.println("ObjectOutputStream successfully initiated");
} else {
System.out.println("ObjectOutputStream is null but did not return an exception when being instantiated");
}
} catch (IOException ioe) {
System.out.println("Could not initialize ObjectOutputStream: " + ioe.getMessage());
}
}`
The problem within this method is that NONE of the System.out.println() methods are getting called, even though, at least to my knowledge, one for each of the streams should be getting called. For example, when instantiating the ObjectInputStream, it should either throw an Exception (which it apparently does not because the System.out.println() is not getting called), returning null (which also does not seem to be the case because the System.out.println() is not getting called) or successfully create the ObjectInputStream object, which it does not because the System.out.println() is not getting called. Why does it not run into any of these situations? Am I missing another situation that might occur?
P.S. Yes, the initializeStreams() method is being called from the program, I just checked it putting a System.out.println() at the very first line of the method.
Thank you
Try to write something on the console in the finally-cluster.
What possibly could be is that an exception is thrown, which doesn't get catched.
But you would see that...wouldn't you.
My first tip: Debug your program, that's what often helped me.
But you could also try this:
private void initializeStreams() {
input = null;
output = null;
try {
input = new ObjectInputStream(socket.getInputStream());
}
} catch (IOException ioe) {
System.out.println("Could not initialize ObjectInputStream: " + ioe.getMessage());
}
//just copied the if outside of the try-catch-cluster
if (input != null) {
System.out.println("ObjectInputStream successfully initiated");
} else {
System.out.println("ObjectInputStream is null but did not return an exception when being instantiated");
try {
output = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException ioe) {
System.out.println("Could not initialize ObjectOutputStream: " + ioe.getMessage());
}
if (output != null) {
System.out.println("ObjectOutputStream successfully initiated");
} else {
System.out.println("ObjectOutputStream is null but did not return an exception when being instantiated");
}
}`
Thats one thing I would try in order to find out what or where the problem is.
Even if it doesn't make that much sense ;)
Well, you catch only IOException. There might be RuntimeException for instance in your code. You won't get to your catch block in this case.
Change IOException to Exception and you will see the reason.
new ObjectInputStream() can throw exceptions other than IOException, but your try-catch only captures IOException. What happens if the exception thrown is one of the other types?
Replace IOException with the Exception class which is the parent of all exception classes.Whatever may be the exception,it will surely get caught using Exception class in catch block.
So replace catch (IOException ioe) this with catch (Exception ioe) everywhere in your code.Then u may find where is the exception coming from.
Assuming Java6, is this code safe from file descriptor leak:
{
InputStream in = fileObject.getReadStream();
// fileObject cleans it's internal state in case it throws exception
try {
// do whatever, possibly throwing exception
} finally {
try {
in.close();
} catch (Exception ex) {
// failure to close input stream is no problem
}
}
}
Edit: To make question seem less obvious, to state it other way, is above code equal to this longer code:
{
InputStream in = null;
try {
in = fileObject.getReadStream();
// fileObject cleans it's internal state in case it throws exception
// do whatever, possibly throwing exception
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
// failure to close input stream is no problem
}
}
}
}
That is, does it matter whether a call to a method which returns opened stream or throws exception is immediately before try, or inside the try block?
Yes, fine. Does not even merit an answer. A variant (I less use) is:
InputStream in = null;
try {
in = fileObject.getReadStream();
// do whatever, possibly throwing exception
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
// failure to close input stream is no problem if everything else was ok
}
}
}
I'm a student not very familiar with Java, but I wish I can help you a litltle.
I think that the piece of code can't keep you from the problem of file descriptor leak. Though you have let a try clouse wurround the in.close methord, but that won't help if
the in.close method throws some exceptions.
The general rule of exceptions is that you catch more specific ones before catching general ones. I have a case where closing a server throws SocketException: socket closed coming from my listener which is caught by IOException, but I don't want to show the user that message when they close the server. Everything else is probably an actual error so it should be shown to them, so I catch SocketException, check its message and if it is not socket closed then it should be rethrown to be caught and handled as an IOException. Java/NetBeans 7.0.1 do not seem to like that. Here is my code:
public void run() {
while (runner == Thread.currentThread()) {
System.out.println("waiting for connection...");
try {
Socket s = server.accept(); //throws SocketException/IOException
if (session == null) {
session = new ReceiveSession(s, parent);
} else {
s.close();
}
} catch (SocketException e) {
if (!e.getMessage().equals("socket closed")) {
throw e; //error line, "unreported exception SocketException"
}
} catch (IOException e) {
e.printStackTrace();
parent.showError("Someone tried to connect but the connection failed: " + e);
session = null;
}
}
}
When trying to clean and build, I get:
error: unreported exception SocketException; must be caught or declared to be thrown
throw e;
1 error
Since SocketException extends IOException, it should be caught by the more general IOException. Why do I get this error? (Running the project as is in NetBeans works perfectly btw, it doesn't show the user the exception when the server shuts down as I want.)
Your throw is outside the try block, so the thrown exception will not be handled by the catch below.
The second catch will not catch the rethrow since it wasn't thrown in the try block for which the second catch is responsible. You'll need to restructure the code.
For example, the most straight forward restructuring would be this:
public void run() {
while (runner == Thread.currentThread()) {
System.out.println("waiting for connection...");
try {
try {
Socket s = server.accept(); //throws SocketException/IOException
if (session == null) {
session = new ReceiveSession(s, parent);
} else {
s.close();
}
} catch (SocketException e) {
if (!e.getMessage().equals("socket closed")) {
throw e; //error line, "unreported exception SocketException"
}
}
} catch (IOException e) {
e.printStackTrace();
parent.showError("Someone tried to connect but the connection failed: " + e);
session = null;
}
}
}
The nested tries make me cry a little, but it would get the job done (and to be honest, off the top of my head, I can't think of a better way that doesn't go way too far).
Catch statements catch exceptions from their respective try block, not from other catch blocks in the list. You're throwing the exception from outside the try, so it does not get caught by subsequent catch blocks.
I have a problem understanding how the try{} catch(Exception e){...} works!
Let's say I have the following:
try
{
while(true)
{
coord = (Coordinate)is.readObject();//reading data from an input stream
}
}
catch(Exception e)
{
try{
is.close();
socket.close();
}
catch(Exception e1)
{
e1.printStackTrace();
}
}
Section 2
try
{
is.close();
db.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Let's say my while() loop throws an error because of an exception of is stream.
This will get me out of the infinite loop and throw me in the first catch(){............}
block.
My question is the following:
After throwing an exception, getting out of the loop while() and reaching to
catch(){
}
Will my program continue his execution and move on to section 2? As long as the exception was caught? Or everything ends in the first catch()?
I think you want to use finally after your first catch [catch (Exception e)] to close your streams:
try {
// Do foo with is and db
} catch (Exception e) {
// Do bar for exception handling
} finally {
try {
is.close();
db.close();
} catch (Exception e2) {
// gah!
}
}
As long as no exceptions are thrown in your catch clause, your program will continue execution after your catch (or finally) clause. If you need to rethrow the exception from the catch clause, use throw; or throw new Exception(ex). Do not use throw ex, as this will alter the stack trace property of your exception.
After the exception is caught, execution continues after the try/catch block. In this case, that's your section 2.
An uncaught exception will terminate the thread, which might terminate the process.
Yes, you are right. It will move to Section 2.
If you want your Section 2 bound to happen, irrespective of any exception generated, you might want to enclose them in a finally block.
try {
// Do foo with is and db
}
catch (Exception e) {
// Do bar for exception handling
}
// Bound to execute irrespective of exception generated or not ....
finally {
try {
is.close();
db.close();
}
catch (Exception e2) {
// Exception description ....
}
}