Throw custom Exceptions in Java/Android - java

I'm developing a custom Exception class, in which I have the following constructors:
public class UserException extends Exception
{
string message;
public UserException() {
super();
}
public UserException(String message, Throwable cause)
{
super(message, cause);
this.cause = cause;
this.message = message;
}
}
And I create a new custom exception like this:
private Camera.PreviewCallback SetPreviewCallBack() throws UserException {
.......
// Something went wrong
throw new UserException("Something failed.", new Throwable(String.valueOf(UserExceptionType.CaptureFailed)));
}
But when I insert my throw new UserException(...) it tells me to surround it with try/catch!! That's not the idea, isn't it? I want to throw custom exceptions when I need them to be thrown, without surronding my new Exceptions with more try/catch clauses.
So, what I'm doing wrong? What I'm misunderstanding?

In addition to Eran's answer, you could also make your custom Exception extend RuntimeException, which does not need to be caught.

If the method that throws this exception doesn't handle it (i.e. it doesn't catch it), it must declare it in the throws clause, since this is a checked exception.
public void yourMethod () throws UserException
{
...
throw new UserException("Something failed.", new Throwable(String.valueOf(UserExceptionType.CaptureFailed)));
...
}

if your Custom Exception extends from Exception class, it must be handled (using try-catch) or passed on to caller (using throws). If you just want to leave it to runtime to handle the exception, You need to extend it from RuntimeException Class
Since its the 1st case in your scenario, You should do something like this:
public void surroundingMethod() throws UserException{
throw new UserException("Something failed.", new Throwable(String.valueOf(UserExceptionType.CaptureFailed)));
}
this will essentially pass your exception to the caller, so now it will be caller's responsibility to handle it with try-catch or pass it on again.
so again, u need to modify calling instruction as
public void callingMethod () {
try {
surroundingMethod();
} catch (UserException ex){
}
}

You should either declare your methods as throws UserException - or make your exception extend RuntimeException.
The later is officially unadvised, but is often used to bypass the java's declared exception mechanism.

In Java, when you throw a checked Exception, there is one more thing you are required to do:
1. Either add a try-catch block around the throw and handle this Exception within the same method.
2. Or add a throws statement to the method definition, transferring the responsibility for the handling of the the Exception to a higher-level method.
This is part of the overall OOP paradigms of modularity & abstraction: who is responsible for handling an Exception, the caller of a method or the method itself ? The answer depends on the nature of the Exception.

Related

When and where to use throws instead of a try catch in Java? [duplicate]

Are these code statements equivalent?
Is there any difference between them?
private void calculateArea() throws Exception {
....do something
}
private void calculateArea() {
try {
....do something
} catch (Exception e) {
showException(e);
}
}
Yes, there's a huge difference - the latter swallows the exception (showing it, admittedly), whereas the first one will let it propagate. (I'm assuming that showException doesn't rethrow it.)
So if you call the first method and "do something" fails, then the caller will have to handle the exception. If you call the second method and "do something" fails, then the caller won't see an exception at all... which is generally a bad thing, unless showException has genuinely handled the exception, fixed whatever was wrong, and generally made sure that calculateArea has achieved its purpose.
You'll be able to tell this, because you can't call the first method without either catching Exception yourself or declaring that your method might throw it too.
They differ in where the responsibility to deal with the Exception lies. First one just throws Exception, so it does not handle it. The code that calls the method needs to handle the Exception. Second one catches and handles the Exception within the method, so in this case the caller doesn't have to do any exception handling, provided showException() itself does not throw another exception.
Yes. The version which declares throws Exception will require the calling code to handle the exception, while the version which explicitly handles it will not.
i.e., simply:
performCalculation();
vs. moving the burden of handling the exception to the caller:
try {
performCalculation();
catch (Exception e) {
// handle exception
}
Yes, there is a great deal of difference between them. The in the first code block, you pass the exception to the calling code. In the second code block you handle it yourself. Which method is correct depends entirely on what you are doing. In some instances, you want your code to handle the exception (if a file isn't found and you want to create it, for instance) but in others, you want the calling code to handle the exception (a file isn't found and they need to specify a new one or create it).
Generally speaking as well, you don't want to catch a generic exception. Instead, you'll want to catch only specific ones, such as FileNotFoundException or IOException because they can mean different things.
There is one particular scenario where we cannot use throws, we have got to use try-catch.
There is a rule "An overridden method cannot throw any extra exception other than what its parent class is throwing". If there is any extra exception that should be handled using try-catch.
Consider this code snippet.
There is a simple base class
package trycatchvsthrows;
public class Base {
public void show()
{
System.out.println("hello from base");
}
}
and it's derived class:
package trycatchvsthrows;
public class Derived extends Base {
#Override
public void show() {
// TODO Auto-generated method stub
super.show();
Thread thread= new Thread();
thread.start();
try {
thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// thread.sleep(10);
// here we can not use public void show() throws InterruptedException
// not allowed
}
}
When we have to call thread.sleep() we are forced to use try-catch, here we can not use:
public void show() throws InterruptedException
because overridden method can not throw extra exceptions.
If you threw an exception, the child method (which overrides this) should handle the exception
example:
class A{
public void myMethod() throws Exception{
//do something
}
}
A a=new A();
try{
a.myMethod();
}catch Exception(e){
//handle the exception
}
I assume that by "identical" you are referring to behavior.
A behavior of a function can be determined by:
1) Returned value
2) Thrown exceptions
3) Side effects (i.e changes in the heap, file system etc)
In this case, the first method propagates any exception, while the second throws no checked exception, and swallows most of the unchecked exceptions as well, so the behavior IS different.
However, if you guarantee that "do something" never throws an exception, then the behavior would be identical (though the compiler will require the caller to handle the exception, in the first version)
--edit--
From the point of view of API design, the methods are completely different in their contract. Also, throwing class Exception is not recommended. Try throwing something more specific to allow the caller to handle the exception better.
Many times you want the caller to handle the exception. Let's say you have the caller call a method which calls another method which calls another method, instead of having each method handle the exception, you can just handle it at the caller. Unless, you want to do something in one of the methods when that method fails.
The caller of this method will need to either catch this exception or declare it to be rethrown in it's method signature.
private void calculateArea() throws Exception {
// Do something
}
In the try-catch block example below. The caller of this method doesn't have to worry about handling the exception as it has already been taken care of.
private void calculateArea() {
try {
// Do something
} catch (Exception e) {
showException(e);
}
}
private void calculateArea() throws Exception {
....do something
}
This throws the exception,so the caller is responsible for handling that exception but if caller does not handle the exception then may be it will given to jvm which may result in abnormal termination of programe.
Whereas in second case:
private void calculateArea() {
try {
....do something
} catch (Exception e) {
showException(e);
}
}
Here the exception is handled by the callee,so there is no chance of abnormal termination of the program.
Try-catch is the recommended approach.
IMO,
Throws keyword mostly used with Checked exceptions to convince
compiler but it does not guarantees normal termination of program.
Throws keyword delegate the responsibility of exception handling to
the caller(JVM or another method).
Throws keyword is required for checked exceptions only ,for unchecked
exceptions there is no use of throws keyword.

Why must I use try catch when I use global exception handling?

I'm beginner in Java and Android. My problem is when I use setDefaultUncaughtExceptionHandler in my code, some functions still need a try/catch block surrounding it, but I want throw all my exceptions to UncaughtException thread.
public class MyAlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(context));
try
{
String imageURL = MyWebService.readFeed();
DownloadAndSet.downloadFile(imageURL);
}
catch(Throwable e)
{
throw new RuntimeException(e);
}
Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show();
}
}
Java distinguishes checked and unchecked exceptions. Checked Exceptions have to be caught, no matter what.
Correction: Or you have to add the throws clause to the method. This postpones the urge to catch that exception to the caller of your method.
If you want them to be handled in the UncaughtExceptionHandler, you can "forward" them:
try{
// blah "throws some checked exception type"
} catch ( Throwable e ) {
// throw e; <- This will not work :( unless you add the "throws" clause.
throw new RuntimeException(e);
}
Unfortunately, just throwing the same Exception won't work, because you'd have to add the throws clause, which you do not want. You'll have to wrap it in a RuntimeException.
All checked exceptions in your code must be caught.
Further reading on checked vs unchecked exceptions:
http://www.javapractices.com/topic/TopicAction.do?Id=129
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
When you call a method that throws an exception, requires you to either handle the exception using try/catch or throw the same exception.
As you don't want to handle the exception in your code and want all exceptions to be handled by your Default Exception handler so you need to add throws to all your methods where you don't want to catch the exception.
The documentation says:
Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.
It doesn't relate to exceptions you have to catch. An example of an exception you have to catch/throw is IOException. An example of an exception you don't is NullPointerException.
So if your code causes a NullPointerException, the default handler will deal with it. If your code (potentially) causes an IOException, you have to deal with it then and there (either by catching or throwing).
What I have always done in my programs is create a exception handler method and call it every time I make a try/catch block. Many times I have had Thread.sleep() methods and I just send the exception to a common place to do "global" handling. In your global exception handler, you can also refer to this method.
Keep in mind that you might not always want to use this method because things like file streams might throw errors if a file already exists and you would want to take a different approach such as naming it something else than just stopping the program.
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
catchException(e);
}
});
try {
Thread.sleep(1000);// Just an example of a possible exception thrower
}
catch (InterruptedException e) {
catchException(e);
}
}
public static void catchException(Throwable e) {
// Deal with the exception here
System.out.println("Oh no! You broke the program!!!");
System.out.println("Here is the error btw: " + e.getMessage());
}
If you are using Eclipse, you can set the default automatic code generation for try/catch blocks to automatically include this method:
You can also set project specific settings if you don't want this behaviour for all of your projects.

Custom Exception class shows Unreachable catch block everytime

I've created a custom Exception class that I want to use in my application:
public class MyException extends Exception {
private static final long serialVersionUID = -2151515147355511072L;
private String message = null;
public MyException() {
super();
}
public MyException(String message) {
super(message);
this.message = message;
}
public MyException(Throwable cause) {
super(cause);
}
#Override
public String toString() {
return message;
}
#Override
public String getMessage() {
return message;
}
}
But when I try to use this class, like below, it gives a compile time error.
try {
System.out.println("this");
} catch (MyException e) {
// TODO: handle exception
}
Compile time error:
Unreachable catch block for MyException . This exception is never thrown from the try statement body
My question is if I'm extending Exception class & calling super in all constructors, then why this error is occurring?
Obviously, you are not doing anything that'd generate a MyException. First write a method with the signature throws MyException, call it and then your problem is solved. Here is an example:
public void someMethod()throws MyException
{
//some condition here.
//if met..
throw new MyException("cause");
}
and modify your main code as:
try {
someMethod();
System.out.println("this");
} catch (MyException e) {
// TODO: handle exception
}
The exception you created is a checked exception and must be thrown from somewhere to catch it.
Any exception created by a java developer by extending Exception class is a checked exception. And the rules applicable for checked exception will be applied on such exceptions.
Another form of exception is called Unchecked Exception and usually created by extending RuntimeException Class. A developer is free to catch such exception without an explicit need for throwing it somewhere from your code.
class Exception is also not thrown generally. I just want MyException behave like Exception.
This is what being further asked in one of the comments:
My take on this is you can think Exception class as a large container which have many different and unique(to the point) child exceptions defined. And mostly these fine grained exceptions are thrown from Java Code. In a abstraction hierarchy, Exception is at higher level (not Highest as, Throwable is sitting there).
Further, as a developer we all are always interested into the finer details like what kind of Exception is thrown. However, while handling exception, we sometimes write
try{
//some code lets assume throws IOException
//Some code lets assume throws FileNotFoundException
}
catch (Exception ex) {
//common handling which doesn't care if its IOException or FileNotFoundException
}
You can not intervene in this exception hierarchy by just writing MyException extends Exception. By this what you are doing is your MyException is a type of Exception not itself Exception class. So, you can't replace Exception caught in catch with your MyException.
Can you try with:
try {
System.out.println("this");
throw new MyException();
} catch (MyException e) {
// TODO: handle exception
}
Your exception wasn't thrown anywhere in the code. (try extending RuntimeException as another option)
What the compile time error says is right "This exception is never thrown from the try statement body". You don't have anything which throws MyException

What happens if a method throws an exception that was not specified in the method declaration with "throws"

I've never used the "throws" clause, and today a mate told me that I had to specify in the method declaration which exceptions the method may throw. However, I've been using exceptions without problems without doing it, so, why is it needed if, in fact, it's needed?
Java has two different types of exceptions: checked Exceptions and unchecked Exceptions.
Unchecked exceptions are subclasses of RuntimeException and you don't have to add a throws declaration. All other exceptions have to be handled in the method body, either with a try/catch statement or with a throws declaration.
Example for unchecked exceptions: IllegalArgumentException that is used sometimes to notify, that a method has been called with illegal arguments. No throws needed.
Example for checked exceptions: IOException that some methods from the java.io package might throw. Either use a try/catch or add throws IOException to the method declaration and delegate exception handling to the method caller.
If a method is declared with the throws keyword then any other method that wishes to call that method must either be prepared to catch it or declare that itself will throw an exception.
For instance if you want to pause the application you must call Thread.sleep(milliseconds);
But the declaration for this method says that it will throw an InterruptedException
Declaration:
public static void sleep(long millis) throws InterruptedException
So if you wish to call it for instance in your main method you must either catch it:
public static void main(String args[]) {
try {
Thread.sleep(1000);
} catch(InterruptedException ie) {
System.out.println("Opps!");
}
}
Or make the method also declare that it is throwing an exception:
public static void main(String args[]) throws InterruptedException {
Thread.sleep(1000);
}
It can happen, even with checked exceptions. And sometimes it can break logging.
Suppose a library method uses this trick to allow an implementation of Runnable that can throw IOException:
class SneakyThrowTask implements Runnable {
public void run() {
throwSneakily(new IOException());
}
private static RuntimeException throwSneakily(Throwable ex) {
return unsafeCastAndRethrow(ex);
}
#SuppressWarnings("unchecked")
private static <X extends Throwable>X unsafeCastAndRethrow(Throwable ex) throws X {
throw (X) ex;
}
}
And you call it like this:
public static void main(String[] args) {
try {
new SneakyThrowTask().run();
} catch (RuntimeException ex) {
LOGGER.log(ex);
}
}
The exception will never be logged. And because it's a checked exception you cannot write this:
public static void main(String[] args) {
try {
new SneakyThrowTask().run();
} catch (RuntimeException ex) {
LOGGER.log(ex);
} catch (IOException ex) {
LOGGER.log(ex); // Error: unreachable code
}
}
You need to declare checked exceptions that your method throws.
If you declare 'throws Exception' that pretty much covers most if not all checked exceptions
You can always throw an unchecked runtime exception and not have to declare.
Im pretty sure if you try to throw a checked exception, and haven't declared the method as throwing that type, the code wont even compile (checking now).
EDIT, right so if you try something simple like
public static void main(String[] args) {
throw new Exception("bad");
}
you get a compile error.
Specifically for your question, if you invoke a method that is declared to throw Exception(s) you must either try/catch the method invocation, or declare that your method throws the exceptions.
The throws key word is used to throw an exception to another method.
It eases the handle exception to the user. Because then all of the exceptions can be handled in a method which is used to run.
Mostly it is mainly a method, so that the user does not need to explore inside the method.
It also throws keyword force to the compiler to handle the exception which could be occurring.
If you were a API developer, when you write a code, you might see that an exception could occur, so you use the throws keyword to handle it when the method runs.
Java throws keyword,
Java throws keyword is used to declare an exception.
throws is followed by class.
Checked exception can be propagated with throws.
It provides information to the caller of the method about the exception.
throws example,
void m()throws ArithmeticException{
//method code
}

Magic Exception thrower without declaring throws Exception

I want a method that can throw any Throwable including sub classes of Exception. Ive got something that takes an exception, stashes it in a thread local, then invokes a class.newInstance. That class ctor declares that it throws Exception then takes the threadlocal and throws it. Problem is it does not work for the two declared Exceptions thrown by Class.newInstance() namely IllegalAccessException and InstantiationException.
Im guessing any other method using some sun.* class is just a hack and not really reliable.
Wrapping is not an option because that means catchers are catching a diff type and that's just too simple and boring...
static public void impossibleThrow(final Throwable throwable) {
Null.not(throwable, "throwable");
if (throwable instanceof RuntimeException) {
throw (RuntimeException) throwable;
}
if (throwable instanceof Error) {
throw (Error) throwable;
}
try {
THROW.set((Exception) throwable);
THROWER.newInstance();
} catch (final InstantiationException screwed) {
throw new Error(screwed);
} catch (final IllegalAccessException screwed) {
throw new Error(screwed);
} finally {
THROW.remove();
}
}
private final static Class<Impossible> THROWER = Impossible.class;
private final static ThreadLocal<Exception> THROW = new ThreadLocal<Exception>();
static private class Impossible {
#SuppressWarnings("unused")
public Impossible() throws Exception {
throw THROW.get();
}
}
From Java Puzzlers (puzzle 43):
public static void impossibleThrow(Throwable t)
{
Thread.currentThread().stop(t); // Deprecated method.
}
The book shows other methods of achieving the same problem, one is a simplified version of yours, the other exploits generic type erasure to throw any Throwable where an Error is expected.
If you want an Exception to bubble up through code not expecting that exception then just wrap it in a RuntimeException
} catch (RuntimeException e) {
throw e; // only wrap if needed
} catch (Exception e) {
throw new RuntimeException("FOO went wrong", e);
}
Remember to let the message be informative. Some day you will have to fix a bug based only on the information in the stack trace.
Wrapping an exception inside a RuntimeException (as suggested by Thorbjørn) is the way to go. However, you usually want to maintain the stacktrace of the original excpetion. Here's how:
public static void rethrow(final Throwable t)
{
if(t instanceof RuntimeException)
throw (RuntimeException) t;
RuntimeException e = new RuntimeException(t);
e.setStackTrace(t.getStackTrace());
throw e;
}
I patched javac to remove the error, compiled impossibleThrow(), renamed the source file to something that does not end in .java (which forces the next compile to use the existing .class) and used that.
There is some validity for this question as a debugging tool. Suppose you are working with some code that may have failed and you see that it (perhaps) catches certain exceptions and (perhaps) throws certain exceptions. You suspect that an unexpected exception was not caught. However, the underlying code/system is too complex and the bug is too intermittent to allow you to step through in the debugger. It can be usefull to add the throwing of an exception without changing the method in any other way. In this case, wrapping the exception with a RuntimeException would not work, because you want the calling methods to behave normally.

Categories

Resources