Android - general exception catcher - java

I'm trying to integrate Facebook into my app so I followed all the instructions. When running it, after onResume event finishes, I get an exception that I can't catch from my code.
Is there a way to set a general exception catcher so no matter what, it will catch it?
The emulator does not throw any exception at all so I can't use it for this
Update: I found it here: Using Global Exception Handling on android
The error came from Facebook itself and it is related to working with proguard

try this solution:
create a class that implement Thread.UncaughtExceptionHandler (this
class going to handle with the uncaughtExceptions), lets call this
class ExceptionHandler.
create a class that extends Application,
lets call this class App, and don't forget to declare this in the
manifest file under application tag: android:name="your_package_path.App"
in your App class override the method onCreate(), and add this line: Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

The Throwable class is the superclass of all errors and exceptions in the Java language.
If you catch a throwable you can catch all kind of errors and exceptions.
try {
// code
} catch(Throwable e) {
// handle throwable
}
However this is strongly not recommended and bad practise/design. You should never catch generic errors and exceptions. You should analyse your specific exception and solve the problem instead of simply ignoring it with try/catch!

There is a base Exception class. So if you do like this:
try {
...anything...
}catch(Exception e) {
e.printStackTrace();
}
you'll catch any exception that is thrown by any method called from within the try block.
But remember that exceptions aren't always thrown. Sometimes there's just no result to return, or something.

Related

run some logic after exception happen dynamically

I think that all Error and Exception type extend from Exception class so how could i watch exception when the application stopped working because i want to run some logic when the exception thrown
i am not just asking about try{} catch {} finally {}
if i want to make plugin to watch on any exception happen on application to run my logic
example
if you have application named X and you have library named Y how could library Y watch and run logic when X throw Exception without edit on logic of X code
Error and Exception classes are extended from Throwable class. Now If you want to catch exception, you can simply go with try-catch-(finally , If required) block. You must not catch Error, because error is something which you cannot recover, Below is the hierarchy, the Error and Exception are two different hierarchy except one thing that both are Throwable.
You can catch exception if you know the exception and execute your logic there. Or, you can write your logic in finally block after exception block. Eg:
try {
....
} catch (YourException e) {
....
} finally {
// your logic
}

Java-Exception Handling

I would like to discuss one thing is that , when an exception is occurred in the body of run method in thread then where it will be reflected(Caller) and how to handle this.
here is my code:
class MyThread extends Thread{
public void run() throws IllegalInterruptedException{
Thread.currentThread().sleep(1234);
}
}
then who(Caller) will manage this exception.
There are 2 different cases :
JVM passes the exception to an exception handler, if already installed for the ThreadGroup.
Otherwise the JVM handles it.
Sample program :
public class ThreadGroupDemo extends ThreadGroup {
public ThreadGroupDemo() {
super("This is MyThreadGroupDemo");
}
public void uncaughtException(Thread t, Throwable ex) {
// Handle your exception here ....
}
}
Thread t = new Thread(new ThreadGroupDemo(), "My Thread") {
// Some code here ......
};
t.start();
NOTE : Check out this link.
If I understood good you want to be able to handle exceptions that are fired in another thread. Take a look at setDefaultUncaughtExceptionHandler, one page with sample:
Java2S
You can see run() like main() and get yourself your answer.
But I don't think you can override run() and declare new nonRuntime-Exceptions .. so you'll get a compile error.
ps: I can't find IllegalInterruptedException, maybe you wanna say InterruptedException
Exceptions are thrown by programs when something out of the ordinary occurs. A general tutorial is available here, but the summary is that your program will search within the class that throws the exception with hopes of finding something to handle it: probably a catch statement like:
catch (IllegalInterruptedException e) {
//what you want the program to do if an IllegalInterruptedException
//is thrown elsewhere and caught here. For example:
System.err.println( "program interrupted!" + e.getMessage() );
}
If your program can't find a catch statement in the class that throws the statement, it will look for something to handle it in a parent class. Be aware that whatever the child class was doing when an exception is thrown stops when it throws an exception. For this reason, you should enclose the block of code that may throw an exception in a 'try' block, and follow it with whatever you want to have execute in a 'finally' statement, which will execute no matter what.
The tutorial linked above is really helpful.
Yet another option - make the task a Callable and use Executors to submit it. You'll then get any exceptions wrapped automatically when you get the Future.

relax exception catch necessity

Is there a possibility in Java to get rid of the necessity to catch non-RuntimeException exceptions? Maybe compiler flags?
I know the reason why the catching is promoted, but want to do simple and straight tools that enforce their requirements. So if something can went wrong I don't like to catch up but exit the application, crashing with a meaningful exception. Usually this ends up like:
try {
connection.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
which introduces 4 lines of code mess, and introduces the wrapping RuntimeException mess on error output. Sometimes it even motivate people to wrap large try ... catch (Throwable ..) blocks around anything, which is the likely cause for our beloved 'Unknown error occured' alert boxes...
you can use throws keyword with method prototype to avoid try-catch block. which eventually throws the exception to JVM's Default Exception handler which halts the application if no catch block's are specified in your code to handle the exception raised.
Crashing the application at the first sight of an exception is very bad practice. Especially when some work is unsaved and the application is using some resources that needs to be freed and cleaned before the application terminates execution. Some very popular software used to do that... and instead of "fixing" the issue, they introduced a data recoverability features on application restart. However the trick, this is not good software engineering.
At the very least, your application should not crash on the first exception/error encountered, but recover with a meaningful message. It is being lazy to just wrap everything in a RuntimeException (or even Throwable) and, especially, not do anything with it.
Java does not support flags of any kind because there are 1) a workaround, and 2) better ways to handle this situation. For example :
1. Handle the exception in the calling method
You can add the throws keyword in your method declaration, up to your static public void main method, which, if not handling the exception, will eventually crash the application with a stacktrace.
class Foo {
public void someMethod(....) throws IllegalArgumentException, IOException {
...
}
static public void main(String...args) throws Throwable {
new Foo().someMethod();
}
}
This method does not offer any means of recoverability and will probably make your user unhappy (with a big meaningless stachtrace if they ran the application from a console, or just nothing at all if they launched it from a shortcut or GUI). Also, if you have some acquired resources, you will not be able to clean them when an exception occurs. At the very least, your main should catch (Throwable e) and output something before throwing the exception above. Something like :
class Foo {
public void someMethod(....) throws IllegalArgumentException, IOException {
...
}
static public void main(String...args) {
try {
new Foo().someMethod();
} catch (...) {
// output or log exception here and, optionally, cleanup and exit
}
}
}
** EDIT **
Consider this scenario : a program is initializing some resource for processing some data, then some runtime exception (or error) occurs during processing, the application crash, but the resources are not released or freed. In Java, however, one could do this
public E doSomething() throws RuntimeException {
// declare a bunch of resources
try {
// process resources with unchecked exceptions
} finally {
// free resources
}
// return some result
}
and cleanly exit the method on error or on success, perhaps even logging the runtime error for "posterity".
2. Log the error and return some meaningful value
Logging is a very good practice. You can show your user some message telling them that the operation could not be executed without crashing the whole thing, and giving you some traces of what and where the user were doing. A simplistic logging system could be :
class Foo {
static private final Logger LOG = Logger.getLogger(Foo.class.getName());
public boolean doSomethingImpl(...) {
boolean result = true;
try {
...
} catch (SomeException e) {
LOG.log(Level.SEVERE, "meaningful message why method could not do something!", e);
result = false;
}
return result;
}
public void doSomething() {
if (!doSomethingImpl(...)) {
// handle failure here
}
}
}
By default, the Logger will output everything to the err output stream, but you can add your own handlers :
// loggers are singletons, so you can retrieve any logger at anytime from
// anywhere, as long as you know the logger's name
Logger logger = Logger.getLogger(Foo.class.getName());
logger.setUseParentHandlers(false); // disable output to err
logger.addHandler(new MyHandler()); // MyHandler extends java.util.logging.Handler
Java already ships with some default logging handlers, one of which writes to file.
etc.
Is there a possibility in Java to get rid of the necessity to catch non-RuntimeException exceptions?
For a checked exception, you can chose between catching the exception and declaring it in the method header as thrown.
Maybe compiler flags?
No. There are no compiler flags to relax this. It is a fundamental part of the language design. Relaxing the checked exception rules via a compiler switch would cause serious library interoperability problems.
I don't think that there's any way around this for the JVM. Your best bet is to have your methods re-throw the exception, which gets rid of the "mess" in your code, and then have your main program throw Exception. This should propagate the error up to the top of your program.
Keep in mind, however, that the place where the exception actually happens is a much better place to let the user know what happened (i.e., exactly what it was doing when this particular IOException happened). You'll lose this resolution if all errors are simply propagated up to the top level.
You do have the ability to throw your exceptions up a level. Here's an example
public class Foo {
public Foo() {
super();
}
public void disconnect(connection) throws IOException {
connection.close();
}
}
Use "Throws" to avoid the error..but it will not be good programimg practice

Avoid try/catch on Android

I am new in Android environment and I have started writing some code to execute some queries on a database. When I have to handle exceptions I don't know what the appropriate way is to do it - out of Android I used to use throws declaration on methods but it seems that throws isn't allowed in android? Just try-catch?
I say this because eclipse doesn't suggest me adding throws declaration like when I am out of Android environment, I guess that it is related to extends Activity.
So what is the appropriate way to handle exceptions in android? Surrounding every sentence with try-catch makes my code look terrible and that's not really what I want to do.
If the method you are using already throws an exception, you may want to just re-throw the exception as the new type:
public void someMethod() throws IOException {
try {
// Do database operation
} catch (MyException e){
throw new IOException(e.toString());
}
}
// Or, if there is no exception, use an unchecked exception:
public void otherMethod() {
try {
// DB operation
} catch (MyException e){
throw new RuntimeException(e);
}
}
The other option is to make MyException extend RuntimeException. Then the compiler won't force you to catch it or add it to the method signature. RuntimeExceptions are known as unchecked exceptions meaning you don't have to check for them occurring by way of a try/catch. Examples of these are NullPointer and ArrayOutOfBounds.
I just was wondering about some strange handling of "throws" in Android environment and found this old question here.
Asker Jon "started writing some code to execute some querys on a database", so maybe he noticed the same as I did.
This compiles without error:
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DbMeta.T_DISGUISED.T_CREATE);
}
Despite this declaration (in javadoc popup):
void android.database.sqlite.SQLiteDatabase.execSQL(String sql) throws SQLException
So first, monkjack is right when he points out that onCreate method's signature cannot be changed by inheriting implementations.
And second, Zeki is correctly indicating the difference between checked and unchecked exceptions.
And now third, I want to add that the big confusion is caused by SQLException.
The SQLException used in the example above is Android type android.database.SQLException and inherits java.lang.RuntimeException - it is an unchecked exception! No throws declaration required!!!
That is not the classic java.sql.SQLException - which is a java.lang.Exception and requires try/catch/throws.
The reason you can't "add the throws in android via eclipse" is because you are not the person who defines the interfaces or super classes. If you want to add an exception to the method signature (like you say you do normally) it also needs to be added to the interface and you are not in control of them so you can't change it.
Eg the method
protected void onCreate(Bundle savedInstanceState);
which you override in activity, if you want to throw an exception the method signature would need to be changed to (for example)
protected void onCreate(Bundle savedInstanceState) throws MyException;
but then it would also need to change where onCreate is defined, which is in the Activity class - and that is a class you can't change (because its provided by the android library).
Therefore your only option is to catch the Exception and do something with it (or just ignore it). You could make a toast to display the errror
catch (Exception e) {
Toast toast = Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
toast.show();
}

How can I detect when an Exception's been thrown globally in Java?

How can I detect when an Exception has been thrown anywhere in my application?
I'm try to auto-magically send myself an email whenever an exception is thrown anywhere in my Java Desktop Application. I figure this way I can be more proactive.
I know I could just explicitly log and notify myself whenever an exception occurs, but I'd have to do it everywhere and I might(more likely will) miss a couple.
Any suggestions?
You probobly don't want to mail on any exception. There are lots of code in the JDK that actaully depend on exceptions to work normally. What I presume you are more inerested in are uncaught exceptions. If you are catching the exceptions you should handle notifications there.
In a desktop app there are two places to worry about this, in the event-dispatch-thread (EDT) and outside of the EDT. Globaly you can register a class implementing java.util.Thread.UncaughtExceptionHandler and register it via java.util.Thread.setDefaultUncaughtExceptionHandler. This will get called if an exception winds down to the bottom of the stack and the thread hasn't had a handler set on the current thread instance on the thread or the ThreadGroup.
The EDT has a different hook for handling exceptions. A system property 'sun.awt.exception.handler' needs to be registerd with the Fully Qualified Class Name of a class with a zero argument constructor. This class needs an instance method handle(Throwable) that does your work. The return type doesn't matter, and since a new instance is created every time, don't count on keeping state.
So if you don't care what thread the exception occurred in a sample may look like this:
class ExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
handle(e);
}
public void handle(Throwable throwable) {
try {
// insert your e-mail code here
} catch (Throwable t) {
// don't let the exception get thrown out, will cause infinite looping!
}
}
public static void registerExceptionHandler() {
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
System.setProperty("sun.awt.exception.handler", ExceptionHandler.class.getName());
}
}
Add this class into some random package, and then call the registerExceptionHandler method and you should be ready to go.
The new debugging hooks in Java 1.5 let you do this. It enables e.g. "break on any exception" in debuggers.
Here's the specific Javadoc you need.
Check out Thread.UncaughtExceptionHandler. You can set it per thread or a default one for the entire VM.
This would at least help you catch the ones you miss.
If you're using a web framework such as Spring then you can delegate in your web.xml to a page and then use the controller to send the email. For example:
In web.xml:
<error-page>
<error-code>500</error-code>
<location>/error/500.htm</location>
</error-page>
Then define /error/500.htm as a controller. You can access the exception from the parameter javax.servlet.error.exception:
Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
If you're just running a regular Java program, then I would imagine you're stuck with public static void main(String[] args) { try { ... } catch (Exception e) {} }
If you are using java 1.3/1.4, Thread.UncaughtExceptionHandler is not available.
In this case you can use a solution based on AOP to trigger some code when an exception is thrown. Spring and/or aspectJ might be helpful.
In my current project I faced the similar requirement regarding the errors detection. For this purpose I have applied the following approach: I use log4j for logging across my app, and everywhere, where the exception is caught I do the standard thing: log.error("Error's description goes here", e);, where e is the Exception being thrown (see log4j documentation for details regarding the initialization of the "log").
In order to detect the error, I use my own Appender, which extends the log4j AppenderSkeleton class:
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
public class ErrorsDetectingAppender extends AppenderSkeleton {
private static boolean errorsOccured = false;
public static boolean errorsOccured() {
return errorsOccured;
}
public ErrorsDetectingAppender() {
super();
}
#Override
public void close() {
// TODO Auto-generated method stub
}
#Override
public boolean requiresLayout() {
return false;
}
#Override
protected void append(LoggingEvent event) {
if (event.getLevel().toString().toLowerCase().equals("error")) {
System.out.println("-----------------Errors detected");
this.errorsOccured = true;
}
}
}
The log4j configuration file has to just contain a definition of the new appender and its attachement to the selected logger (root in my case):
log4j.rootLogger = OTHER_APPENDERS, ED
log4j.appender.ED=com.your.package.ErrorsDetectingAppender
You can either call the errorsOccured() method of the ErrorsDetectingAppender at some significant point in your programs's execution flow or react immidiately by adding functionality to the if block in the append() method. This approach is consistent with the semantics: things that you consider errors and log them as such, are detected. If you will later consider selected errors not so important, you just change the logging level to log.warn() and report will not be sent.
In this case I think your best bet might be to write a custom classloader to handle all classloading in your application, and whenever an exception class is requested you return a class that wraps the requested exception class. This wrapper calls through to the wrapped exception but also logs the exception event.
I assume you don't mean any Exception but rather any uncaught Exception.
If this is the case this article on the Sun Website has some ideas. You need to wrap your top level method in a try-catch block and also do some extra work to handle other Threads.
Sending an email may not be possible if you are getting a runtime exception like OutOfMemoryError or StackOverflow. Most likely you will have to spawn another process and catch any exceptions thrown by it (with the various techniques mentioned above).
There is simply no good reason to be informed of every thrown exception. I guess you are assuming that a thrown exception indicates a "problem" that your "need" to know about. But this is wrong. If an exception is thrown, caught and handled, all is well. The only thing you need to be worried about is an exception that is thrown but not handled (not caught). But you can do that in a try...catch clause yourself.

Categories