I have a class with severeal methods which extract data from a sqlite database. I would like to "force" the users of this class to call these methods in a thread or an asynctask.
How can i prevent a method to run on the main thread ?
I would like to achieve something similar to the android.os.NetworkOnMainThreadException thrown when you try to do some networking on the ui thread.
- The main method should simply terminate if any exception occurs. The throws clause only states that the method throws a checked FileNotFoundException and the calling method should catch or rethrow it. If a non-checked exception is thrown (and not catch) in the main method, it will also terminate.
Uncaught exception handler will be used to demonstrate the use of exception with thread. It is a specific interface provided by Java to handle exception in the thread run method. There are two methods to create a thread: Extend the thread Class (java.
Yes, We can throw any exception in the run() method. What happens when an exception occurs in a thread in Java?
Yes, it can be done by using Thread. UncaughtExceptionHandler. When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler usingThread.
Do something like:
if (Looper.myLooper() == Looper.getMainLooper()) {
throw new DontDoThisOnUiThreadPleaseException();
}
Source: Looper.getMainLooper() and Looper.myLooper().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With