Your current method covers the first point - to take an exception as parameter.
The throws Exception is unnecessary if you dont throw it from a method, but it is needed to cover the second point.
As commenters pointed, you just need to use the throw keyword to throw an exception, so the method could look like:
public void throwException (Exception ex) throws Exception {
//some other code maybe?
throw ex;
}
This implementation has a little flaw. When the null is passed as a parameter to it, the method will throw a NullPointerException, because the throw keyword accepts objects of the Throwable class or its subclasses (Exception is a subclass of Throwable).
To avoid NullPointerException (which is an unchecked-exception), simple if statement can be used:
public void throwException (Exception ex) throws Exception {
if (ex != null) {
throw ex;
}
//just for presentation,below it throws new Exception
throw new Exception("ex parameter was null");
}
Edit:
As @Slaw suggested, in that very small case adding the null-check and throwing new Exception just disguises the NullPointerException. Without the null-check and throw new... the NPE will be thrown from that method and its stacktrace will show exact line of throw ex when the null is passed to that method.
The NPE is a subtype of RuntimeException class and the subtypes of RuntimeException doesn't need to be explicitly declared in method signature when they are thrown from that method. Like here:
public static void throwNPE(Exception e) {
throw new NullPointerException();
}
The RuntimeException and its subclasses are called an unchecked-exceptions. Other classes extending one of Exception or Throwable classes are call checked-exceptions, because if a method throws them, it must declare that exception (or superclass) in the signature or explicitly try-catch it.
The proper use of null-check would be when the method would throw a more specific kind of exception (like IOException or a new subclass of Exception/Throwable) and the when the other method using the one which throws that new type of Exception would try-catch that specific type the NPE wouldn't be caught.
Just for good practices, when dealing with try-catch it's much better to catch exact types of thrown Exceptions instead of general Exception/Throwable. It helps to understand the real cause of exception, debug and fix code.
Answer from itwasntme on Stack OverflowHow to throw a checked exception from a java thread? - Stack Overflow
Explicitly throwing the exception in java in method calls - Stack Overflow
java - Why is "throws Exception" necessary when calling a function? - Stack Overflow
When to throw an exception? When to try and catch and exception.
Videos
To be able to send the exception to the parent thread, you can put your background thread in a Callable (it allows throwing also checked exceptions) which you then pass to the submit method of some Executor. The submit method will return a Future which you can then use to get the exception (its get method will throw an ExecutionException which contains the original exception).
Caveat: this may not meet your needs if you have to use the exception mechanism.
If I understand you correctly, you don't actually need the exception to be checked (you've accepted the answer suggesting an unchecked exception) so would a simple listener pattern be more appropriate?
The listener could live in the parent thread, and when you've caught the checked exception in the child thread, you could simply notify the listener.
This means that you have a way of exposing that this will happen (through public methods), and will be able to pass more information than an exception will allow. But it does mean there will be a coupling (albeit a loose one) between the parent and the child thread. It would depend in your specific situation whether this would have a benefit over wrapping the checked exception with an unchecked one.
Here's a simple example (some code borrowed from another answer):
public class ThingRunnable implements Runnable {
private SomeListenerType listener;
// assign listener somewhere
public void run() {
try {
while(iHaveMorePackets()) {
doStuffWithPacket();
}
} catch(Exception e) {
listener.notifyThatDarnedExceptionHappened(...);
}
}
}
The coupling comes from an object in the parent thread having to be of type SomeListenerType.
Throwing an exception is done by simply using the throw keyword:
public void someMethod()
{
if(something)
{
}
else
{
throw new SomeException("My Custom Message");
}
}
You can throw an exception from anywhere in your code, not only in the else statement.
Never throw Throwable instance. The Throwable class is the superclass of all errors and exceptions.
For exception, Throw Exception or RuntimeException (for difference see java tutorial. link is given below)
Throw Errorfor serious problems. Errors should not be caught or handled (except in the rarest of cases)
An
Erroris a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
See Java Tutorial for exception for more details and explanations
In Java, as you may know, exceptions can be categorized into two: One that needs the throws clause or must be handled if you don't specify one and another one that doesn't. Now, see the following figure:

In Java, you can throw anything that extends the Throwable class. However, you don't need to specify a throws clause for all classes. Specifically, classes that are either an Error or RuntimeException or any of the subclasses of these two. In your case Exception is not a subclass of an Error or RuntimeException. So, it is a checked exception and must be specified in the throws clause, if you don't handle that particular exception. That is why you needed the throws clause.
From Java Tutorial:
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
Now, as you know exceptions are classified into two: checked and unchecked. Why these classification?
Checked Exception: They are used to represent problems that can be recovered during the execution of the program. They usually are not the programmer's fault. For example, a file specified by user is not readable, or no network connection available, etc., In all these cases, our program doesn't need to exit, instead it can take actions like alerting the user, or go into a fallback mechanism(like offline working when network not available), etc.
Unchecked Exceptions: They again can be divided into two: Errors and RuntimeExceptions. One reason for them to be unchecked is that they are numerous in number, and required to handle all of them will clutter our program and reduce its clarity. The other reason is:
Runtime Exceptions: They usually happen due to a fault by the programmer. For example, if an
ArithmeticExceptionof division by zero occurs or anArrayIndexOutOfBoundsExceptionoccurs, it is because we are not careful enough in our coding. They happen usually because some errors in our program logic. So, they must be cleared before our program enters into production mode. They are unchecked in the sense that, our program must fail when it occurs, so that we programmers can resolve it at the time of development and testing itself.Errors: Errors are situations from which usually the program cannot recover. For example, if a
StackOverflowErroroccurs, our program cannot do much, such as increase the size of program's function calling stack. Or if anOutOfMemoryErroroccurs, we cannot do much to increase the amount of RAM available to our program. In such cases, it is better to exit the program. That is why they are made unchecked.
For detailed information see:
- Unchecked Exceptions — The Controversy
- The Catch or Specify Requirement
Java requires that you handle or declare all exceptions. If you are not handling an Exception using a try/catch block then it must be declared in the method's signature.
For example:
class throwseg1 {
void show() throws Exception {
throw new Exception();
}
}
Should be written as:
class throwseg1 {
void show() {
try {
throw new Exception();
} catch(Exception e) {
// code to handle the exception
}
}
}
This way you can get rid of the "throws Exception" declaration in the method declaration.
Hello, I am lookign for a clear example of when you throw an exception and how to use it do you catch that thrown exception somewhere or does it end there. When do you use try and catch block for exceptions? I understand the concept of exceptions but that part isn't very clear to me. One method throws it other method catches it and so on.