Java exception class for failed thread start - java

I have a thread that opens a socket at the beginning of its run method, after which it enters into a listening loop. I want the run method to throw a RuntimeException that tells me that the thread failed to start.
Is there such an exception type in Java? Something like ThreadStartFailedException?
Note: I don't want to open the socket in its constructor because I need this thread to be restartable, i.e. when I call interrupt on it, it gracefully closes its socket; if run is reinvoked on the same instance, the socket is recreated and the thread is running as if it were its first time.

Yes there is a RuntimeException class. But throwing exception from run method and if you need to catch it later outside of the run method and it's corresponding class context, you will need to use Callable instead of Runnable.
Is there such an exception type in Java? Something like
ThreadStartFailedException?
Nope, there is no such exception exists by default. Check the subclasses of RuntimeException from the documentation. You can subclass the RuntimeException if you want.
class ThreadStartFailedException extends RuntimeException
{
public ThreadStartFailedException(String message) {
super(message);
}
}

Related

Why is main() method allowed to declare exceptions?

"Handle or declare. That's the law." - Head First
But, is it a good law? Let me give an example first:
public static void main(String[] args) throws Exception {
m1();
}
static void m1() throws Exception{
m2();
}
static void m2() throws Exception {
throw new Exception();
}
m2() throws exception and m1() calls m2(), meaning it must either handle or declare it. Hmmm let's declare it. Then main() calls m1() and it has same poll: declare or handle. I again decided to declare it and code compiles just fine.
Okay, it works, but who handled this exception at all? Looks like no one did. I know I am a beginner, but I don't like the sound of that. Yes, some methods can decide whether to declare or handle exceptions, but why main()? Shouldn't main method be one that just handles? In that way, no exception could "slip".
Am I missing something to this? I was honestly surprised that it is okay for main method to just declare exception, knowing that it is the last place we could technically catch something.
who handled this exception at all?
The Java runtime did.
More specifically, the UncaughtExceptionHandler did, as specified in the Java Language Specification (JLS), section 11.3. Run-Time Handling of an Exception:
If no catch clause that can handle an exception can be found, then the current thread (the thread that encountered the exception) is terminated. Before termination, all finally clauses are executed and the uncaught exception is handled according to the following rules:
If the current thread has an uncaught exception handler set, then that handler is executed.
Otherwise, the method uncaughtException is invoked for the ThreadGroup that is the parent of the current thread. If the ThreadGroup and its parent ThreadGroups do not override uncaughtException, then the default handler's uncaughtException method is invoked.
So, by default, when main() throws an exception, unchecked or checked, the built-in default "uncaught exception handler" will simply print the stacktrace to System.err, as-if the following was executed right before main() was called:
Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler());
class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
#Override
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace();
}
}
After the "uncaught exception handler" has been invoked the thread is terminated, same as if you simply return from the main() method, and unless the code has started non-daemon threads that are still running, the program ends.
Application may contain more than one class with main method. In that case application should declare a manifest to know which main is entrypoint (first called method). Main method can be called from another methods or another main method as a static method and can throw any exception. If you don't catch exception at least in entrypoint, then exception returned from your application to java virtual machine, then mashine deside what todo with exception. Usually jvm prints error message and return value other than 0 to operating system.

Android RuntimeException is occurring silently and not being logged

So I have some code that's throwing a RuntimeException. I know it's throwing a RuntimeException, I wrote it to do so under certain circumstances. Recently, I was having what I thought was a deadlock, because the method didn't seem to be finishing, but as I logged out the problem I realized that it was in fact that RuntimeException.
Now, here's the issue: This exception is occurring silently. The Android monitor in Android Studio isn't displaying a stack trace for it. This threw me off, because in normal Java applications (which I'm more used to, I'm a professional Java dev but I'm a bit new to Android), RuntimeExceptions send a stack trace directly to the console.
So, my reaction was to do a Thread.UncaughtExceptionHandler to log this. Only... it's not working.
Here's my UncaughtExceptionHandler. I don't actually care about it doing all the things it does, I was just trying to get something to happen to indicate that it was being called.
public static class ContactsUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
private static final String TAG = "UncaughtException";
#Override
public void uncaughtException(Thread thread, Throwable throwable) {
System.out.println("UNCAUGHT EXCEPTION"); //TODO delete this
Log.e(TAG, String.format("Uncaught exception in thread %d", thread.getId()), throwable);
throwable.printStackTrace();
System.exit(1);
}
}
This handler is being added in the following ways:
1) I have an executor spawning threads. It uses a ThreadFactory, which assigns this handler to each thread using Thread.setUncaughtExceptionHandler().
2) I call Thread.setDefaultUncaughtExceptionHandler() in the onCreate() method of my Application class.
3) The code where this is occurring is a Runnable.run() method. I put a line in that run() method calling Thread.currentThread().setUncaughtExceptionHandler().
Nothing works. None of those operations there get triggered.
I know with 100% certainty that a RuntimeException is occurring, because if I surround the code with a try-catch block and do printStackTrace() that way, it shows up in the console log. I just can't get the UncaughtExceptionHandler to work.
The code where this is happening is very long and verbose, here's a quick summary of it:
#Override
public void run(){
Thread.currentThread().setUncaughtExceptionHandler(new ContactsThreadFactory.ContactsUncaughtExceptionHandler());
System.out.println("This line outputs to the console");
object.callingMethodThatCausesException();
System.out.println("This line never executes, because exception was thrown");
}
Any ideas on how to fix this? I don't understand why it's not working.
Edit: Just discovered something interesting, not 100% sure what it means yet. I put "throws new RuntimeException()" into the onCreate() method of my Activity class, and that exception showed up in the console like normal. I tried doing the same thing from within that Runnable, and nothing. Not entirely sure what to make of that.
Also, the UncaughtExceptionHandler worked for that new RuntimeException I put in. I just don't understand why it's not working elsewhere?

How to log an error in the console if one of the callables of the executor service encounter an error

I have a program which uses executorService to which I am passing callables.
Each of which is an object of one class which implements java.util.concurrent.Callable.
Then the executorService is invoked. A java.lang.NoClassDefFoundError is thrown in the middle of one of the callables in the call() method.
However it is not terminating nor getting logged on the console. Therefore there is no way to know if the program has worked correctly or not. Kindly suggest any way by which I can understand the same.
A Callable throws an Exception, which is not the superclass of NoClassDefFoundError. Within your Callable, catch Error (or even Throwable) and wrap it with an Exception:
V call() throws Exception
{
try
{
return this.doSomething();
} catch (Error e) {
e.printStackTrace();
throw new Exception(e);
}
}
In order to print the error to the console, you can create a Thread.UncaughtExceptionHander. Passing it into the Thread#setDefaultUncaughtThreadExceptionHandler will cause the handler to be invoked when the error is thrown.
Some one had already posted answer to this question, but when I came to mark it as answer after verifying, the post was unfortunately deleted. I am just retyping the answer.
The Futures which are returned by the ExecutorService after calling the invoke method contain all the Future objects of the thread. If anything goes wrong in any of the threads, an java.util.concurrent.ExecutionException is thrown. Which can be detected in the parent thread which owns the executorService when we do get() on the Future. Then e.getCause() after catching it will get us the actual object which caused an error/exception.

Java, default exception messages

Given the following:
public abstract class Test {
public static void main(String[] args) {
int[] testArray = {6, 3, 2};
System.out.println(testArray[3]);
}
}
when I run the program I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Test1.main(Test1.java:5)
In this case the JVM displays the index that is out of bounds i.e. 3.
This specific example aside, given that I choose not to catch an exception in a program's code:
How can I find out, for any exception, either checked or unchecked, what the default message would be that the JVM would display?
For a custom exception class that I write myself, and for an object of this class that I generate in my code using the 'throw' keyword (but, again, choose not to catch), can I set up a default message that the JVM would display?
How can I found out, for any exception, either checked or unchecked, what the default message would be that the JVM would
display?
As you might already suspect, the answer is "in general, you can't". Most of the time, the message is set from one of the constructors of the exception that takes a string message. If you're lucky, the message will be meaningful and provide useful information. Otherwise, as is common practice, the semantics of the exception will reside essentially in its class name and in the associated Javadoc. Also consider that exception messages are often localized.
For a custom exception class that I write myself, and for an object of this class that I generate in my code using the 'throw' keyword
(but, again, choose not to catch it), can I set up a default message
that the JVM would display?
That's entirely up to you. You could setup a default message in the default constructor like this:
public class MyException extends Exception {
public MyException() {
super("my default message");
}
public MyException(String message) {
super(message);
}
}
There is Thread.setDefaultExceptionHandler, all the uncaught exceptions will go there, so you can provide your own exception handler as an argument to that method somewhere in the beginning of your program.
I think, you can also construct any exception yourself and see the message as follows
new IOException().getMessage()
though probably the message in that case will be empty, I didn't try
I am only able to answer your second question.
In your Exception class (which should derive from java.lang.Exception) add (overwrite) the constructor accepting a String as an argument. Pass the message you want your thrown exception to have as a String to the new constructor et voilà → you got a personalized message for your exception. If you need a default message, just use this constructor from within the default one. Hope that helps.
Any exception that is of type or extends runtime exception is unchecked exception. Rest are checked exception.
You just need to extend runtime exception then you need not handle the exception that is thrown. And you can print default message for that exception by ovveriding getMessage method.

Adding 'throws' on an extended class?

I'm making a simple application with the Socket API, but have run into a small issue that I haven't found the answer for.
The application is supposed to be multi-threaded, so that the main method starts both the server and client threads.
public class UDPClientServer1 extends Thread
However, since the the Socket classes need to throw some specific exceptions, I must also do this:
public void runClient() throws SocketException, UnknownHostException, IOException
and similarly for the runServer() method.
Not that there's anything wrong with that, but is there a more elegant solution? Something along the lines of :
public class UDPClientServer1 extends Thread, throws Exception
Ideally you may want to wrap the exception that your throw, either converting it to a RuntimeException if the error is unrecoverable, or at least a more appropriate / encapsulated exception.
E.g.
public void runClient throws ClientException
{
try
{
// do something
} catch (Exception e)
{
log.error("Exception encountered in client",e);
throw new ClientException("Unrecoverable client exception encountered",e);
// or: throw new RuntimeException("Unrecoverable client exception",e);
}
}
ClientException in the above is your own exception that you would need to create. Its purpose is to encapsulate the implementation details of corresponding exceptions from any calling code.
Using a RuntimeException, however, may be more appropriate if there is no reasonable way for the calling code to respond to the exception. When throwing a RuntimeException you do not have to declare it in the method signature and calling code does not need to explicitly handle it (although it should be handled at some point).

Categories

Resources