Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i have following code and i like to get exception message using finally as by using catch i can easily get by its arg.but as much i know i am not able in get exception message using finally.
try {
MyClass obj=new MyClass();
obj.strProName = jobj1.getString("productname");
obj.strPrice = jobj1.getString("price");
obj.strCurrency = jobj1.getString("currency");
obj.strSalePrice = jobj1.getString("saleprice");
obj.strStoreName = jobj1.getString("storename");
//arrayList.add(obj);
throw new Exception("Exception Reason!");
}
finally{
//want to get that exception message here without using catch or can see how finally catching here the exception
}
Unlike catch block ,finally block does'nt receive any exception instance
So,The answer is No from my side.
What I mean is to print the message,You need Exception instance.
As per docs (jls-14.2)
A block is a sequence of statements, local class declarations, and local variable declaration statements within braces.
So outside of catch block catch(Exception e) {} you cannot access it (e).
but as much i know i am not able in get exception message using
finally.
That's correct, to catch an excpetion you, well... have to use a catch clause.
You could however store the message in a variable (in the catch clause) and use that variable in the finally clause later.
finally does not catch the exception. You can catch exception only in catch block.
The purpose of finally block is to execute in both cases, i.e. it will execute irrespective of exception being occured or not.
Finally does not catch exception, it is simply a thing you can use to always do something, even if there is no error and the catch is never called for.
try {
MyClass obj=new MyClass();
obj.strProName = jobj1.getString("productname");
obj.strPrice = jobj1.getString("price");
obj.strCurrency = jobj1.getString("currency");
obj.strSalePrice = jobj1.getString("saleprice");
obj.strStoreName = jobj1.getString("storename");
}
//arrayList.add(obj); here you can Catch the exception, meaning it will only show if there is an exception!
catch(Exception e){
System.out.print(e+"=Exception Reason!");
}
finally{
//Finally is used to do something no matter what.
//It will do what ever you want it to do,
//even if the catch is never used.
//Use catch to show exception,
//finally to close possible connections to db etc.
}
Try this
try {
.....
throw new Exception("Exception Reason!");
}
catch(Exception e){
msg=e.getMessage();
finally{
//USE String msg here.
}
Related
This question already has answers here:
Exception thrown in catch and finally clause
(12 answers)
Closed 1 year ago.
I have this piece of Java code.
void convertFile() {
try{
.....
}catch (Exception e) {
logError("Error in convertJsonFile", e);
throw e;
}finally{
if (writer!=null) {
writer.close();
writer = null;
}
if (fos!=null) {
fos.close();
fos = null;
}
ms2 = System.currentTimeMillis();
logInfo(String.format("Time elapsed: %d seconds.", ((ms2-ms1)/1000)));
logInfo("File conversion complete.");
}
return f + "_changed.xml";
}
The catch block logs and rethrows the Exception.
But it seems the finally block also throws a RuntimeException.
Will the finally block be executed if the catch block rethrows Exception as done here?
If I remember correctly finally block will be executed even in this case.
OK if so... what will happen if we enter the catch block (it rethrows), then we enter the finally block, and the finally block also throws a RuntimeException at this line writer.close(); ? Which exception will be thrown from this whole method - the rethrown one from the catch block, or the RuntimeException from the finally block?!
I think the RuntimeException will be the final outcome of the method and we will never reach the line in the catch block which rethrows. Because I guess the line which rethrows is executed after the finally block. But I am not sure. I got really confused.
Could someone clear my doubts here?
Seems I have forgotten some of these details.
And I have no decent access to the logs, they are in Elastic/Kibana and access to them is a real pain.
Yes, finally block will be executed
The exception from finally block will be thrown in this case. Thus, exception from catch block will be lost.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
There are a number of ways to catch "Exceptions" in programming. It's always advisable to catch "known" exceptions inside programs without simply catch Exception.
To reduce unnecessary repetitive code fragments we can catch multiple exceptions at once and do further steps. I could find simple 2 methods to do that.
method 1:
catch (IOException ex){
System.out.println("Exception found");
throw ex;
}
catch (FileNotFoundException ex){
System.out.println("Exception found");
throw ex;
}
method 2:
catch (IOException|FileNotFoundException ex){
System.out.println("Exception found");
throw ex;
}
Which one is the better method to handle multiple exceptions at one in java? is there any better method to do that?
Please note, that you have to catch FileNotFoundException before catching IOException because a FileNotFoundException is an IOException. Otherwise you will never reach the FileNotFoundException. So in your case you could only catch IOException because it contains FileNotFoundException.
catch (IOException ex){ // does contain FileNotFoundException
System.out.println("Exception found");
throw ex;
}
Generally speaking: If you have the same code in your catch block, you should use a multi catch because otherwise you'd have duplicated code. I see no problem in that (in fact, that's why multi-catch has been introducted to Java).
But that's not always the case of course. If you have to treat exceptions differently you must define different catch blocks.
There is another method. we can use if condition inside catch block for selection.
catch (Exception ex){
if(ex==IOException){
System.out.println("Exception found");
throw ex;}
else if (ex==FileNotFoundException){
System.out.println("Exception found");
throw ex;}
}
}
This question already has answers here:
Java try/catch/finally best practices while acquiring/closing resources
(8 answers)
Closed 6 years ago.
I am using Apache PDFBox to read some PDF files. When I am done with the PDF's I need to release the PDF documents. To do this I call the close() method which throws an exception. The program also allows to edit the PDF in which case an exception could be thrown but my program just closes them which shouldn't error. In this case is it acceptable to just catch the exception and leave the catch block empty or is there a better way to deal with it?
For example:
try {
pdf.close();
catch {
//empty
}
Is it acceptable to just ignore when a stream close throws exception?
In most cases it is, but it really depends on the context. If you decide not to handle the close exception and are looking to avoid extra try-catch block, then you can use IOUtils from commons-io library.
finally {
IOUtils.closeQuietly(pdf);
}
This is equivalent to the following
finally {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException ioe) {
// ignore
}
}
try {
//code to catch
} catch (IOException ex) {//specific catch
ex.printStackTrace();
} catch (Exception e) {//Catch errors lazily, This will catch any exception within the try that is rooted from the Exception class.
e.printStackTrace();
}
There are more proper ways to do this, but this is a easy way. You really only need one catch clause, you can have multi catch's. Google "how to use Try/catch/finally in java" and you should come up with some good stuff.
Good luck!
I've been looking all over for an answer to this and have yet to find one.
Basically I am trying to connect to a database server through a GUI. My boss wants to be able to enter all fields and then check to see if they are valid entries, then if there are any invalid entries, he wants me to turn the text red, indicating that the field is invalid. I have the try statement catch ClassNotFoundException and SQLException. Because there are multiple fields that need to be checked, I have tried to have a set of if statements to check the connection info. Here is the code below, I hope this makes sense...
//The cancel boolean values in this code are used elsewhere to regulate the Threads
try
{
//attempt connection here
}
catch(ClassNotFoundException | SQLException e)
{
String[] errors = new String[4]; //This will create a String array of the errors it catches
//and will later get called into a method that displays
//the messages in a JOptionPane.showMessageDialog()
if (e.getMessage().startsWith("The TCP/IP connection to the host"))
{
errors[0] = "SQL CONNECTION FAILED: Please check the server URL you entered to make sure it is correct.";
cancel = true;
mGUI.serverNameTextField.setForeground(Color.RED);
}
if (e.getMessage().startsWith("Login failed for user"))
{
errors[1] = "LOGIN FAILED: You do not have sufficient access to the server.";
cancel = true;
}
if (e.getMessage().startsWith("Cannot open database"))
{
errors[2] = "SQL CONNECTION FAILED: Please check the database name you entered to make sure it is correct.";
cancel = true;
mGUI.dbNameTextField.setForeground(Color.RED);
}
mGUI.reportErrors(errors); //Method where it reports the String[] array of errors
//However, the 'errors' parameter only returns one error
//message at a time, which is the problem.
Thanks for any help!
****EDIT******
I found a solution, so hopefully this will help someone. I changed my if statements to add an AND argument checking for the specific error code. You find find the error code by either setting a break point and looking at the debug perspective, or you can do what I did and set a print statement to see the error code. Here is the print statement:
System.out.println(((SQLException) e).getErrorCode());
Here are my new for statements:
try
{
//attempt connection here
}
catch(SQLException | ClassNotFoundException e)
{
if (e instanceof SQLServerException && ((SQLServerException) e).getErrorCode() == 0)
{
//code here
}
else{
//code here
}
System.out.println(((SQLException) e).getErrorCode()); //Here is the print statement to see the error code.
if (e instanceof SQLServerException && ((SQLServerException) e).getErrorCode() == 4060)
{
//code here
}else{
//code here
}
if(cancel != true)
{
//code here
}
}
You can do it in multiple ways
1 having more than one catch with a common function
}catch (ClassNotFoundException e){
handleError(e);
}catch (SQLException e){
handleError(e);
}
where handleError takes the exception as the argument.
You dont seem to do anything else so you can just combine them both into a single exception
}catch(Exception e){
}
which will catch everything but you have MUCH less control over the error handling.
A general principle of exceptions is that they are handled at the point they are best abled to be handled.
You seem to have very disparate exceptions and presumably a TCP exception thrown somewhere in the code is not the same as the SQLException thrown when connecting to a database (I might be wrong here since I don't know what the rest of the code looks like). So would not a set of exception handlers, one for each type make more sense. Also to reite from Bryan Roach, text disambiguation is not a good idea.
try {
...
} catch (java.net.SocketException e) {
e[0] = "tcp error";
} catch (java.sql.SQLException e) {
e[1] = "sql exception happened";
}
Also your string array seems a bit risk, possibly a
ArrayList errors = new ArrayList();
errors.add("Some tcp error");
errors.add("Some db error");
and then for you error reporting
mGUI.reportErrors(errors.toArray())
would preserve your interface and not waste you having to allocate extra elements to the array and have empty entries. I don't know exactly what your question is, but you allude to the GUI not displaying multiple errors. Possibly there is a check which stops at the first empty element in an array. Say e[2] and e[4] is populated, it might stop when it iterates over the errors as e[3] is empty. I'm presuming again since I don't know what that code looks like
From the comments above it sounds like what you want to do is have different logic for the various Exception types you are catching within a single catch block. If this is the case, you could go:
...
catch(ClassNotFoundException | SQLException e) {
String[] errors = new String[4];
if (e instanceof ClassNotFoundException) {
//do something here
}
if (e instanceof SQLException) {
//do something else here
}
...etc
}
This should work, but it's probably just as easy to use multiple catch blocks as others have suggested:
}catch (ClassNotFoundException e){
handleError(e);
}catch (SQLException e){
handleError(e);
}
I don't mean any offense, but the way the code handles exceptions might cause some headaches down the road. For example:
if (e.getMessage().startsWith("Cannot open database")) {
Here the code relies on the supporting library that throws the exception to use the same text description, but this description might change if you switch to another JVM version, use a different database driver, etc. It might be safer to go by the exception type, rather than the exception description.
This questions is related to java exceptions, why are there some cases that when an exception is thrown the program exits even though the exception was caught and there was no exit() statement?
my code looks something like this
void bindProxySocket(DefaultHttpClientConnection proxyConnection, String hostName, HttpParams params)
{
if (!proxyConnection.isOpen())
{
Socket socket = null;
try {
socket = new Socket(hostName, 80);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
proxyConnection.bind(socket, params);
}
catch(IOException e)
{
System.err.println ("couldn't bind socket");
e.printStackTrace();
}
}
}
and then
I call this method like this:
bindProxySocket(proxyConn, hostName, params1);
but, the program exits, although I want to handle the exception by doing something else, can it be because I didn't enclose the method call within a try catch clause? what happens if I catch the exception again even though it's already in the method? and what should I do if i want to clean resources in the finally clause only if an exception occurs and otherwise I want to continue with the program? I am guessing in this case I have to include the whole piece of code until I can clean the resources with in a try statement or can I do it in the handle exception statement?
some of these questions are on this specific case, but I would like to get a thorough answer to all my questions for future reference. thanks
edit:
java.net.UnknownHostException: www.dsewew324f.com
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at homework3.Proxy.bindProxySocket(Proxy.java:666)
at homework3.Proxy$3.handle(Proxy.java:220)
at org.apache.http.protocol.HttpService.doService(HttpService.java:293)
at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:212)
at homework3.Proxy.start(Proxy.java:472)
at homework3.Proxy.main(Proxy.java:1282)
Exception in thread "main" java.lang.IllegalArgumentException: Socket may not be null
at org.apache.http.impl.DefaultHttpClientConnection.bind(DefaultHttpClientConnection.java:80)
at homework3.Proxy.bindProxySocket(Proxy.java:674)
If
socket = new Socket(hostName, 80);
throws an exception then socket will be null and
proxyConnection.bind(socket, params);
will throw a NullPointerException, which you do not catch.
Are you sure the exception was caught? Your catch block only catches certain exceptions. A Runtime exception could be getting thrown which would not be caught..
Could it be that your program is simply coming to it's natural conclusion (exits from the main method)?
If your program is exiting because of an exception thrown from the main method then it should be printed to the console. Can you provide this stack trace?
May be that proxyConn is null, and because
if (!proxyConnection.isOpen())
it is not in a try/catch block it may generate an unhandled exception that causes your program to exit.
To answer some of your questions: what happens if I catch the exception again even though it's already in the method?
To put it simply, you can't. Once an exception is caught once, it is no longer on the top of the stack so any further attempts to catch it will fail
what should I do if i want to clean resources only if an exception occurs and otherwise I want to continue with the program?
If you want to do some action, any action, only when an exception occurs you should do this in your catch block.
I am guessing in this case I have to include the whole piece of code until I can clean the resources with in a try statement or can I do it in the handle exception statement?
I already answered this question with the one above :P
Like I said in my comment on marcus' post you should put a try catch around the call to the function itself to ensure that any other exceptions are being caught. You can figure out what to do from there when you know what exceptions aren't being caught.
try{
bindProxySocket(proxyConn, hostName, params1);
}
catch(Exception e){
e.printStackTrace():
}
You shouldn't continue the code after an exception which may cause that the code cannot continue.
Rewrite your code as follows:
Socket socket = null;
try {
socket = new Socket(hostName, 80);
try
{
proxyConnection.bind(socket, params);
}
catch(IOException e)
{
System.err.println ("couldn't bind socket");
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Better practice is just to let that exception go and declare a throws in your method. You should only handle the exception where it makes sense to handle it. Don't suppress the exceptions by just printing the trace and then continuing with the program flow.