Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw an exception if a method is executed from main thread

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.

like image 393
grunk Avatar asked Oct 21 '13 14:10

grunk


People also ask

Can we throw exception in main method?

- 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.

How do you handle exceptions in thread main?

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.

Can we throw exception from thread?

Yes, We can throw any exception in the run() method. What happens when an exception occurs in a thread in Java?

How can you catch an exception thrown by another 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.


1 Answers

Do something like:

if (Looper.myLooper() == Looper.getMainLooper()) {
   throw new DontDoThisOnUiThreadPleaseException();
}

Source: Looper.getMainLooper() and Looper.myLooper().

like image 106
kamituel Avatar answered Oct 04 '22 21:10

kamituel