Jruby Stack Traces - java

So this might be a dumb question but I don't know what to ask for since 'jruby print stack trace' googled doesn't come up with much thats worthwhile but,
How does one print the stack trace when writing Jruby code that accesses Java classes that throw exceptions? ie right now I took code from someone else that looks like
rescue JavaSql::SQLException
puts "SQLException"
end
which works, but I'd like to see which particular SQLException is happening like I would in Java (ie. PrintStackTrace(Exception e))? How does one accomplish this?

I've never worked with Java exceptions in Ruby, but AFAIK, Java exceptions get presented to you as Ruby exceptions, which means you can get the exception message by sending the :message message to the exception object:
begin
# stuff
rescue JavaSql::SQLException => e
puts "#{e.class}: #{e.message}"
end
Is that what you mean? I'm not quite sure what you would need the stacktrace for in this particular situation, so I probably misunderstood.

One would imagine it relies on the underlying implementation. If the underlying implementation just swallows the exception you will not be able to see a stack trace. Also why don't you just allow the exception to bubble up in your ruby code so that the trace gets thrown out to the screen?

Related

How ho handle WindowLeaked?

I have WindowManager: android.view.WindowLeaked in stacktrace and I have to handle it.
I know reasons why it appears but fixing it will take too much time.
All I need to catch it like typical exception, something like:
try {} catch (WindowLeaked e) {}
But that doesn't work for sure because it's not Exception.
Is there any way to do it?
I don't ask how to fix it or what is WindowLeaked.
The question is: How can I know that WindowLeak happened?
The answer to your question is that your application cannot "know" when it has happened. Despite its unconventional name, android.view.WindowLeaked is a Java exception. However, it is uncatchable because it not thrown in any context where there is no application code on the call stack.
(Apparently, it is not thrown at all. Rather, it seems to be used as a means of capturing a stacktrace for logging. This does seem rather odd since the stack trace doesn't tell you much ... given that there is no application code on it!)
You (the programmer) can know that it has happened (by reading the logcat!) but there is nothing you can do about it ... apart from tracking down the root cause and fixing it.
Window Leak exception usually occurs when the user have open the view and didn't close the view.

Printing the stack trace vs the exception itself

quick question. Of course the stack trace gives way more information, but is it a bad practice to use the exception itself instead in some cases? Like just getting "null pointer exception" as opposed to this huge dump of stuff? If this doesn't make any sense, the two differences would be:
(Exception e)
{
print e
}
AND
(Exception e)
{
e.printStackTrace
}
I will say use neither of them in production. You should handle exceptions in other ways, like logging the exception or saving the stacktrace somewhere to review it later and probably display a nice message to the user saying that the app or method failed.
But if you just ask about which of those approaches to use, I will say the latter is better because System.out.println(e) will call Throwable#toString that only provides the message of this exception and maybe you won't get the real cause of the problem.
It depends on the context. Anything that will (or even might accidentally) be presented to the user should not include the stack trace. More than being confusing, you could leak potentially sensitive information.
In my code, I create custom exceptions that have a UserFriendlyMessage property. Friendly messages should be in very plain English. I even have a default catch-all friendly message "There was an unexpected problem. You can try again and if the problem continues contact support".
On the other hand, having the stack trace is invaluable for debugging. In my .NET apps, we go so far as to compile our release code in a special way such that the code is optimized but the symbols are still generated in a separate file. We do this for the sole purpose of ensuring full stack traces with line numbers.
So in summary, display only friendly messages but log (and if you are going to, alert) full stack traces + the friendly message.
The difference between them is that print e returns the type of exception and error message while printStackTrace returns the whole stacktrace of the exception. printStackTrace is more beneficial to be used while debugging.
Example:
print e:
java.lang.IndexOutOfBoundsException
e.printStackTrace():
java.lang.IndexOutOfBoundsException: Index: 8, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at com.o2.business.util.Trial.test(CommonUtilsTest.java:866)
printStackTrace might be good for programmer, but it is not readable and user-friendly for end users. As far as I know, printStackTrace prints the results in the default Errorstream: your console. For better practices, you can check the link: http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html

java - is there a standard way of collecting exceptions?

I have a Java program that parses several different input files. Even when an error is found in this input files, parsing could still continue and collect several other errors too. So what I want to do is instead of throwing and exception and stopping parsing process, I'd like to register the exception to somewhere, and then continue parsing and collect several other errors in similar way, then in the end I want to check if any errors are reported, and fail or continue depending on this.
Of course I can always do this manually by writing ExceptionRegister or whatever classes but I want to know two things:
1) Is there a problem with this approach? Do you know any alternative designs for what I want to do?
2) Is there a standard way of doing this? (e.g. instead of rolling my own classes I'd like to use built-in functionality if possible)
Thanks
EDIT: I don't know why but someone just removed his answer just before I accepted his answer. Anyway, I think simple data structures should work. Basically, I'll write an exception class that collects several error messages. Then I'll call it's throw method which throws itself if it has at least one error message registered.
EDIT2: Here are more clarifications. My problem has nothing to do with parsing. Parsing was just an example because my program does some parsing. Think this: I'm running an algorithm and in case of an error, I can continue the algorithm to collect more errors so that instead of printing one error and when it's fixed, printing second error, I can print this two errors together.
Exceptions should really be used when you can't handle the input anymore. They are the special case where your code says "I give up, I'm missing some information or I wasn't meant for this". This is a grey area on how to define such cases, but the usual philosophy, as put by Bill Venners in this (old!) article is:
Avoid using exceptions to indicate conditions that can reasonably be
expected as part of the typical functioning of the method.
In your case, it sounds like the content you have to parse might be incorrect, but this is expected by your program and doesn't break enough the contract to stop the parsing. On the other hand, an acceptable exception would be valid to use if an error in the syntax of the input causes the rest of the interpretation to fail, for example.
But people still uses exception because they are quite convenient for stopping execution and going up the stack without going in the tedious details of flowing through returns of results. But on its counterpart, they can have tricky results as you leave some unattended state in some objects.
Your requirements sounds more like a validation pattern is required than one single exception that could cause the processing to stop. One exception to stop all processing: if you throw one, the rest will be ignored. But you suggested that you would collect them instead of throwing those. So I'd say, in that case, why use exceptions at all? It seems you do want to return proper results and not stop the program's execution.
Because if you still go down this path, you could have a collection of exceptions to throw at the end. Which one do you throw? Which one takes precedence, in the Exception collector you created?
Take the example of Eclipse, which has this gigantic platform to handle with a massive collection plug-ins contribution. They use a proper communication channel to log any warning and errors, either in problems pane or through the execution of background task. The latter's execution will usually return an IStatus object or a variant. Based on this IStatus object, the code that receives the status decides to act upon it.
Hence personally, I'd develop a similar object that would collect all necessary user's errors (and not program's errors), that does not break the program's execution and an acceptable part of the contract. This object can contain the severity of the error, its source, a hint on how to fix it (this can be a string, or even a method that contains a pinpointing logic for showing the error or possibly a partial automated fix), etc... Once the execution is done, the parsing's result will get these status objects and act on it. If there are errors, inform the user through the UI and log it as well.
So it's basically the same approach as you initially suggested, minus the exceptions and minus the commodity of jumping through the stack that could lead to nasty side-effects and very difficult to debug errors.
I think I understand now. What you are actually trying to do is to collect the parse errors (which you are representing as exceptions) and continue parsing the current input file.
There is no standard way to do this:
The "exception register" is really nothing more than a list of parse error descriptors ... presumably some parser exception. If you can catch the exception at the appropriate point, it is trivial to add it to the "register".
The difficult part is the functionality you are not talking about:
How to capture the location of the error
How to get the parser to continue parsing when it gets a parser error.
The solutions to these depend on how you have implemented your parser.
If you are using a parser generator, there is a good chance that the PGS documentation explains how to implement this.
If you are implementing the parser by hand, you will need to roll your own code to track error locations and do syntax error recovery.
Basically, I'll write an exception class that collects several error messages. Then I'll call it's throw method which throws itself if it has at least one error message registered.
That sounds like an abuse of exceptions. A better idea is to accumulate the errors in a list, and then create / throw the exception if the list is non-empty. Use a static method in a helper class if you want to avoid duplicating code.
An exception that conditionally throws itself is (IMO) bizarre! And creating lots of exceptions that you are unlikely to throw is likely to be inefficient. (Depending on the JVM, the expensive part of exceptions is often creating the exception and capturing the stack frames. The expense can be significant.)

What level to use for exception stack trace logging in Java?

I'm looking for best practices document (or your opinions) on how to effectively log exceptions and their stack traces. Of course, assuming one of popular logging frameworkks such as Log4J, SLF4J, java.util.logging, etc.
I'm particularly interested in your opinion about on what level stack traces should be logged.
I heard few contradicting each other opinions such as:
stack traces should be logged only on DEBUG level while ERROR level should contain only "human readable" error message
stack traces should be logged on ERROR level in order to give to the operator maximum amount of information required to find root cause of an exception
I have found couple of interesting articles however none of them touches this particular subject:
http://today.java.net/pub/a/today/2006/04/06/exception-handling-antipatterns.html
http://today.java.net/pub/a/today/2003/12/04/exceptions.html
which probably means that authors of these articles had same concerns as I do :-)
I'd be really interested in your view on this subject.
Stack trace is the most valuable piece of information you get when troubleshooting. I would never risk logging it on DEBUG level since it might be disabled. And I almost never want to suppress stack traces.
Also note that:
log.error("Houston, we have a problem", ex);
will print the human readable message in line marked as ERROR, while the stack trace is following that line. If you want your errors to be only human readable, just do grep ERROR.
I'm not sure about best-practice advice for this, but in the end, for me it boils down to this:
Exceptions should only be visible in exceptional circumstances. The concept of exception was invented to give developers a chance to handle errors internally.
In reality, most code I see doesn't even try to handle them, instead dumping them to the log, sysout, (or worst case of all) into dialog boxes. I know, that for a developer it is important in some cases to get the full stacetrace. But not nearly in all of them. Creating your own exception framework (which is definitely a best practice) might already be enough to figure out the context of an exception simply by classname.
So I would advise to do the following:
Create your own exception framework
Include specific error codes in the message, for your reference
Log the exception message on ERROR
Log the stacktrace on DEBUG
NEVER EVER display the user either of these. Instead show a useful message. Maybe include a way to report the error (with stacktrace) with minimal fuzz.
Note: If you are writing an internal "enterprise" software, forget everything I wrote. :-)
I think the stack trace should be logged at the appropriate place based on priority best practices. Depending on the nature of the exception and its place within your application, this may be one of many levels. Please see this related question:
Commons Logging priority best practices

What's the point of an OurCompanyRuntimeException type in Java?

At the company where I am right now, there are a lot of places in the code where an OurCompanyRuntimeException is thrown (where OurCompany is the actual name of the company). As far as I can tell, this exception is described as "A runtime exception thrown by code that we wrote here at this company."
I'm somewhat new to Java, but I thought exception types were supposed to reflect what went wrong, not whose code threw the exception. For example, IllegalArgumentException means someone passed an illegal argument to something. You wouldn't have a SunIllegalArgumentException if an illegal argument was passed in code written by Sun, and then a IBMIllegalArgumentException -- that would be silly and pointless, right? And if you want to know where the exception was thrown, you look at the stack trace. I understand wanting to extend RuntimeException (so that you don't have as many try/catches or "throws"es all over) but why not make subclasses that explain what happened, as opposed to what company's code it happened in?
Has anyone ever used the OurCompanyRuntimeException idea before, or have an idea of why they might have done it this way?
Sounds like the usual bespoke code nonsense that you find in in-house code bases to me. I suspect if you ask about there'll have been some decree that the OurCompanyRuntimeException was used based on some misguided logic by a senior guy that nobody dared question and has long since moved on - the story of the monkeys, bananas and hose-pipes springs to mind.
I agree with you, the name of the exception should be indicative of the error that has occurred.
Helps when reading stack traces, that's for sure. I.e. when scanning through a lot of lines of 'caused by's', it helps to see that it occurred in something thrown by you, not something internal to, say, a container.
Also lets you perform custom actions as part of the throwable - e.g. write to a special log somewhere, etc.
Yes I encountered that, too, but it didn't make sense to me either. My guess was, that the companies wrote this exceptions very early after the adoption of Java without getting the correct idea of how exception throwing and handling really works (like Nick already said... by the senior programmer nobody dared to question).
If the company feels the need to create its own exception class (e.g. for company specific logging porpuses) this exception should never be thrown directly (making it abstract). I would derive concrete Problem describing Exceptions instead or just follow the Spring Framework's idea for Exception handling/throw.
This is a bad concept. Exceptions should be specific for a use case.
Okay, if the company does produce a lot of faulty code/products, they may use that type of exception as advertisement ;)
Your company might be adding code to an already existing project, like an open source code base, and could have just added very little code to it. So in order to trace errors that happen by the company's developers, they thought that they would have their own exception class to distinguish the errors that were there before, from the ones caused by the extension. This way, they can focus only on the ones that are caused by company's developers, and perhaps ask the original source code maintainers to fix the other ones.
With time, when you people have developed a sufficiently large code base through in-house development, you may add more exceptions and remove the CompanynameRuntimeException altogother. Also, they might get more at ease with the level of expertise of the developers, to allow them to treat all errors like one, and not to view the ones caused by company developers more suspiciously.
It would make very good sense to have this as a baseclass for specific exceptions. You thrown a specific exception and catch the base class.
Also it may allow to carry a cause (the REAL exception) plus additional information around. That can be very handy for creating diagnostic output for logging.
Seems pretty silly, logging output or a stack trace will show you who the offending class is, so that explanation doesn't wash. Also seems dangerous, as if people are encouraged to throw the OurCompanyRuntimeException they're throwing RuntimeExceptions, which don't force the caller to handle them and can take down your application.
I agree with you that exceptions should reflect the reason behind them. I've seen a custom exception as the root of a hierarchy, although it probably ought to be abstract, so that you need to create a specific extension to use one, and it definitely shouldn't be a RuntimeException.
It wouldn't be a bad idea to have a generic company wide exception class like you describe that more specific exception cases inherit from. One answer already mentioned the ability specifically catch internal code exceptions and ignore / pass through the ones from core java or third party library code. The key point here is that more specific exceptions should inherit from this one. Throwing a generic company-named exception would be rarely required, and almost never recommended.

Categories