catch (Exception ex) block misses - java

There are a few similar questions, but for C# mostly.
#Override
public void setExtraItemsDone(XMPPResourceConnection session) throws NotAuthorizedException
{
try
{
cp1 = Calendar.getInstance().getTimeInMillis();
try
{
...
} catch (TigaseDBException e) {
...
} catch (UnsupportedOperationException e) {
...
}
} catch (Exception e) {
cp2 = Calendar.getInstance().getTimeInMillis();
throw new NotAuthorizedException(e.getMessage() + "; method took " + (cp2 - cp1) + " ms", e);
}
I am basically looking to catch a MySQLTimeoutException and turn it into a NotAuthorizedException (while keeping an eye for any other stuff besides TigaseDBException and UnsupportedOperationException) in the last catch block. Somehow, java eludes my master plan.
Logs show a straight
com.mysql.jdbc.exceptions.MySQLTimeoutException: Statement cancelled due to timeout or client request
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1754)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2019)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1937)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1922)
at tigase.db.jdbc.JDBCRepository.addDataList(JDBCRepository.java:183)
at tigase.db.jdbc.JDBCRepository.setDataList(JDBCRepository.java:1175)
at tigase.db.UserRepositoryMDImpl.setDataList(UserRepositoryMDImpl.java:651)
at tigase.xmpp.RepositoryAccess.setDataList(RepositoryAccess.java:1152)
at tigase.xmpp.RepositoryAccess.setOfflineDataList(RepositoryAccess.java:1204)
**at tigase.xmpp.impl.XGateRoster.setExtraItemsDone(XGateRoster.java:370)**
at tigase.xmpp.impl.DynamicRoster.setExtraItemsDone(DynamicRoster.java:377)
at tigase.xmpp.impl.JabberIqRoster.dynamicSetRequest(JabberIqRoster.java:178)
at tigase.xmpp.impl.JabberIqRoster.process(JabberIqRoster.java:329)
at tigase.server.xmppsession.SessionManager$ProcessorWorkerThread.process(SessionManager.java:2135)
at tigase.util.WorkerThread.run(WorkerThread.java:132)
As far as i can tell, the bolded line in the stack trace should have changed the exception to a NotAuthorizedException breed. What am I missing ?
Thanks

I agree. the problem is not with the code as posted. Check your assumptions. Are there other overloadings of XGateRoster.setExtraItemsDone? Try using Jad to decompile the class file you are running against. If you enable the options to show line numbers, you can be sure the (decompiled) source you are viewing is exactly the code that is executing. Do you know exactly where the log message you are looking at comes from? Maybe it comes from higher up the stack, after it is thrown but before this catch block and exception translation code are even hit.

Related

ScriptEngineManager extra cautious exception handling

I wanted to consult about JDK code exception handling,
In ScriptEngineManager from lines 120 there are unused secondary catch for ServiceConfigurationError which can't be thrown as I understand it
try {
while (itr.hasNext()) {
try {
ScriptEngineFactory fact = (ScriptEngineFactory) itr.next();
facList.add(fact);
} catch (ServiceConfigurationError err) {
System.err.println("ScriptEngineManager providers.next(): "
+ err.getMessage());
if (DEBUG) {
err.printStackTrace();
}
// one factory failed, but check other factories...
continue;
}
}
} catch (ServiceConfigurationError err) {
System.err.println("ScriptEngineManager providers.hasNext(): "
+ err.getMessage());
Is there a reason why a second catch will be necessary? it seems it effect only while (itr.hasNext()) which doesn't throw any exception
Or is it just overly cautious to ensure method not throwing exception in any case, as commented
// do not throw any exception here.
Actually java allows you to duplicate such try-catch without any error/warning:
try {
try {
ScriptEngineFactory fact = itr.next();
engineSpis.add(fact);
} catch (ServiceConfigurationError err) {
err.printStackTrace();
}
} catch (ServiceConfigurationError err) {
err.printStackTrace();
}
If I'll concatenate catches in same try I would get compilation error
Unreachable catch block for ServiceConfigurationError. It is already handled by the catch block for ServiceConfigurationError
Minor misconception: the second catch does not only cover the while loop. It would also take care about such exceptions thrown from within the first catch block.
But you are correct: that catch block, as well as the loop "header" should not throw such an exception. It seems rather odd that simply iterating an iterator needs "protection" in such a way.
Thus: maybe this is a leftover when other code existed in that method. Or it is overdoing. Or worst case, the code that we don't see (that creates that iterator) can in fact throwing that kind of error. Which, as said, would be odd and a very bizarre design, to say the least.

Why is there no catch?

Im trying to delete TXT-files, but I always get the same error message. It's nearly the same code as the one I found on the Internet.
for (int i = 0; i < datei.length; i++)
{
try
{
loeschenDatei = datei[i].delete();
if (loeschenDatei)
{
System.out.println(datei[i] + " wurde geloescht!");
}
else
{
System.out.println(datei[i] + " konnte nicht geloescht werden!");
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
I always get the error:
unreachable catch block for ioexception. this exception is never thrown from the try statement body.
This means that nothing within your try block can throw an Exception of type IOException. The only thing that I'm unsure of is datei[i].delete(). Check out that method signature in your IDE and see if at the end it throws IOException or something like that. If that method doesn't throw anything, then remove your try catch block altogether.
unreachable catch block for ioexception - compiler code validation is suggesting that. Possibly IO exceptions already handled in delete method.
In case you are unsure which exceptions may be thrown by your code, you could change IOException to Exception.

Is there a way to throw IOException in a runnable?

I have some code thats not working(which is a common occurrence for me), but because I am not getting an errors it just continues to run with bad data. The problem I think is it keeps telling me to wrap parts of my code in try/catch blocks(my tests are basic, I just output a message in the try area and if it gets outputted I assume all went well. All does not seem well in my code). I understand in production, putting a try/catch statement helps the code to continue to run but its making me troubleshooting difficult because I'm trying to troubleshoot that section of my code.
Is there a way around this so I can actually see when something fails within the try area?
Here's a sample of my code:
try {
ByteArrayInputStream baos_back = new ByteArrayInputStream(message);
ObjectInputStream oos_back = new ObjectInputStream(baos_back);
i = oos_back.readInt();
d = oos_back.readDouble();
list_of_ints = (int[]) oos_back.readObject();
oos_back.reset();
baos_back.reset();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Are you trying to get your program to blow up when this error occurs? If so, you should be able to wrap your IOException in a RuntimeException and throw that instead. They're unchecked, so you don't need to declare them and it should kill your program just fine.
If you want your code to throw the appropriate exception, I'd suggest not using try-catch blocks at all. Try-catch is used to handle exceptions as they arise and then keep running the program, but it sounds like you don't want to handle them at all.
If you do want to use try-catch blocks you could always manually throw a RuntimeException at the end of the catch block.
Something like:
throw new IOException();
try {
// Some code...
} catch(Exception e) {
// Error handling code...
throw new RuntimeException(e.getMessage());
}
As I mentioned in my comment, you can catch all exceptions in Java with a blanket catch statement:
try {
// code
} catch (Exception e) {
e.printStackTrace();
}
This will catch every Exception thrown in the try block, and the only things it won't catch are Errors.
In practice, you will want to limit the types of exceptions you catch, and catch more specific exceptions, so you can exception chain as follows:
try {
// code
} catch (IOException ioe) {
// we expected this
ioe.printStackTrace();
} catch (SomeOtherException soe) { // just an example...
soe.printStackTrace();
} catch (Exception e) {
// Did we expect this? Maybe not!
e.printStackTrace();
}
The above also makes it known that you expect some types of exceptions to occur, and then a big blanket catch-all statement that might catch things you didn't expect.
You can also log exceptions to a file or something else, rather than output them to standard out as this code does right now. A basic logging utility is java.util.logging.
I still recommend learning to use a debugger though. Debuggers can do a lot of things like halt program execution whenever an exception is thrown, and allow you to inspect the values of variables and fields at any point in the program's execution. If you use Eclipse or Netbeans or IntelliJ or other IDEs, they have debuggers. If you use the command line, there is the jdb command-line java debugger.
I suggest editing your code generation template to do this
catch ( $ExceptionClass e )
{
// TODO: Autogenerated catch block
e.printStackTrace();
throw new RuntimeExcepton( e );
}
This way you have a TODO reminder, a barf on stdout, and are ensured that your program will blow up if you do not provide correct exception handler.

Catch Exception in finally { } ? Must?

I feel puzzle ...
I write a small routine in .jsp. Finally, ResultSet, Statement and Connection are required to be closed. I also write the closing codes in finally { }, but when the page is run, it return error that I didn't catch exception ...
I read some forum. Other people didn't catch any exception in finally { }
Any Hint ?
Sounds like you have the old problem of needing to close() in a finally block but close() throws an exception itself. Try somethig like the following...
ResultSet rs;
try {
// do various stuff
rs = ...;
} finally {
try {
if (rs != null) rs.close();
} catch (SQLException e) {
// do something with exception
}
}
You must catch exceptions in the code finally block. As you must catch exceptions in the catch block. Nested try/catches are a regular thing (albeit ugly).
One important note here is that you could have the exceptions that occur in finally declared in the throws clause of the method. However that would lead to the exception in finally overriding the original exception, which is lost. And you will see, for example, a NullPointerException, rather than FileNotFoundException.
By the way, avoid having code in the JSP file. Place it in a servlet.
finally{} doesn't do any exception catching. A finally{} block exists to make sure that certain code is run, no matter whether the try{} block reached its natural end or if it's jumping temporarily to the finally{} because an exception happened and that finally{} block was along the way. But after the finally{} finishes, the exception goes about its merry business, cavorting its way up the stack and cheerfully crashing your program.
If you want to actually catch the exception and stop it from unwinding the stack further, use catch(){}. But don't use catch blindly- catching an exception you don't actually know how to recover from is much worse than crashing, because now your program isn't working correctly and you don't have an exception stack trace telling you why.
Your ResultSet, Statement, and Connection almost certainly did get closed. And then the exception continued happening and crashed your program anyway, because that had nothing to do with your ResultSet, Statement, and Connection.
What was the actual exception?
Maybe I'm getting old, but what's wrong with catching exceptions in the catch block?
It helps if you say what is in your try block. You are probably not catching appropriate exception or your code in finally throws exception.
It is OK to have finally without catch.
try {
//do some work
}
finally {
//check of state and do clean up. You would have reached here via multiple branches.
}
It more appropriate to catch specific exceptions using catch and then handle specific cleanup there. Use finally for any code that must get executed even when exception happen.
try {
//do some work
}
catch ( RecoverableException1 re1) {
//cleanup
}
catch ( RecoverableException2 re2) {
//cleanup
}
finally {
//check of state and do clean up. You would have reached here via multiple branches.
}
finally{
try{
resultSet.close();
}catch(E e){
}finally{
try{
statement.close();
}catch(E e){
}finally{
conn.close();
}
}
}

Java exception handling

How do I use exceptions and exception handling to make my program continue even if an exception occurs while processing certain files in a set of files?
I want my program to work fine for correct files while for those files which cause an exception in program, it should ignore.
Regards,
magggi
for(File f : files){
try {
process(f); // may throw various exceptions
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
You have to use the try/catch/finally blocs.
try{
//Sensitive code
} catch(ExceptionType e){
//Handle exceptions of type ExceptionType or its subclasses
} finally {
//Code ALWAYS executed
}
try will allow you to execute sensitive code which could throw an exception.
catch will handle a particular exception (or any subtype of this exception).
finally will help to execute statements even if an exception is thrown and not catched.
In your case
for(File f : getFiles()){
//You might want to open a file and read it
InputStream fis;
//You might want to write into a file
OutputStream fos;
try{
handleFile(f);
fis = new FileInputStream(f);
fos = new FileOutputStream(f);
} catch(IOException e){
//Handle exceptions due to bad IO
} finally {
//In fact you should do a try/catch for each close operation.
//It was just too verbose to be put here.
try{
//If you handle streams, don't forget to close them.
fis.close();
fos.close();
}catch(IOException e){
//Handle the fact that close didn't work well.
}
}
}
Resources :
oracle.com - Lesson: Exceptions
JLS - exceptions
I guess your new to programming as execeptions are a fairly fundermental concept, as problems can happen out of your control and you need to deal with it.
The basic premise is a try catch block.
try
{
//Your code here that causes problems
}
catch(exception ex)
{
//Your code to handle the exception
}
You 'try' your code, and if an exception is raised, you 'catch' it. And do what you need.
There is also an addition to the catch block in that you can add finally{} below it. Basically even if no exception is raised the finally code is still run. You may wonder the point in this, but its often used with streams/file handling etc to close the stream.
Read more on java exceptions here in tutorials written by Sun (now Oracle)- http://download.oracle.com/javase/tutorial/essential/exceptions/
try
{
//Your code here that causes problems
}
catch(exception ex)
{
//Your code to handle the exception
}
finally
{
//Always do this, i.e. try to read a file, catch any errors, always close the file
}
The question you may ask is how do you catch different exceptions, i.e. is it a null reference, is it divide by zero, is it no file found or file not writeable etc. For this you write several different catch blocks under the try, basically one catch for each type of exception, the use of "exception" is basically a catch all statement, and like in stack of if statements if an "exception" is the first catch block it will catch everything, so if you have several catch blocks ensure exception is the last one.
Again, this is a useful but large topic so you need to read up about it.
Since you are doing multiple files, you need to basically do a loop and within the loop is contained the try/catch block.
so even if one file fails, you catch it, but carry on running, the code will then loop around onto the next file unhindered.
just catch the excpetion it may throw and do nothing with it; eat it as people say :)
But at least log it!
Very concise example:
try {
your code...
} catch (Exception e) {
log here
}
Typically, I would have done this.
ArrayList<Entry> allEntries = getAllEntries();
for(Entry eachEntry:allEntries){
try{
//do all your processing for eachEntry
} catch(Exception e{
ignoredEntries.add(eachEntry);
//if concerned, you can store even the specific problem.
} finally{
//In case of resource release
}
}
if(ignoredEntries.size() > 0){
//Handle this scenario, may be display the error to the user
}
FileSystemException may be the specific exception you are looking for.
Although, a better idea for beginners is to catch an exception and print it using
System.out.println(e);
where e is the caught exception.
public class Main
{
public static void main(String args[])
{
int a=10;
try
{
System.out.println(a/0); //Here it is not possible in maths so it goes to catch block
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception");
}
}
}
output:Arithmetic Exception
Exception in java are runtime error which can be handled by the program, the process is called as exception handling. Parent class of exception is Throwable.
Exception : Exception are those runtime error which can be handled by program.
Error : Those runtime error which can’nt handled by the program.
Tools used to handle Exception:
Try
Catch
Finally
Throw
Throws
more

Categories