Throw Exception in onFailure of LoopJ AndroidAsyncHttp - java

Edited
I have a custom Exception class MyException
public class MyException extends RunTimeException{
public MyException()
{
super();
}
public MyException(String message)
{
super(message);
}
public MyException(Exception e)
{
super(e);
}
}
now whenever an exception is raised I catch it in MyException and throw it back to the parent function. I am facing an issue as I am using AsyncHttpClient and it raises an exception in onFailure as it is raised by the server.
This is how I am making HTTP Request and trying to handle Exception.
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(TIMEOUT);
try {
client.post(mainActivity,
PATH, new StringEntity(requiredDataForRequest),
"application/json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
}
#Override
public void onFailure(int arg0, Header[] arg1,
byte[] arg2, Throwable e) throws MyException {
throw new MyException("Error Description Here!");
}
});
} catch (MyException e) {
log.debug("Exception: " + e.getMessage());
}
Now it is Crashing my app on throw new MyException and not catching it in catch block. Any idea or help would be appreciated.

Because the definition of onFailure does not specify that it throws anything means that none of its implementations can throw a checked exception. You can change your MyException by making it extend RuntimeException, but because it is a runtime exception any callers of onFailure are not required to catch the exception. If you are the only user of this class, that is fine as long as you remember to catch the exception yourself.

You are missing the basic java concept here, you added a throw clause to your onFailure(), but the original method definition does not know what to do if something is thrown!
Basically when you use the throw keyword and throw an exception, then this exception has to be caught at the place where method is called.
Now, since you are overriding onFailure() and the AsyncHttpClient has no catch() for your MyException class, so its simply not getting catched!
If you want to get it catched, write the throw inside a try catch block in your onFailure()
try {
throw MyException();
} catch(MyException e){
// Exception caught
}
this will work as you have a catch for your thrown exception.
Next,In your case you call
try {
client.post(///);
} catch (MyException e) {
// exception caught
}
Now for the exception to be caught it has to be thrown by the client.post method call!
If you look at the post method
public RequestHandle post(android.content.Context context,
java.lang.String url,
org.apache.http.HttpEntity entity,
java.lang.String contentType,
ResponseHandlerInterface responseHandler)
It doesn't throws anything! so your exception will never be called!
And in case you want to catch something, you will either have to modify the library!

Related

How to append custom message to exception (in overrided methods which CANT throw exception)?

I know I can always catch exception in try/catch block and throw Exception (message, e) like this
try {
//...my code throwing some exception
} catch (IndexOutOfBoundsException e) {
throw new Exception("Error details: bla bla", e);
}
Easy. But it doesnt work in overriden methods, because they cant throw any exception with super method doesnt throw.
So, what are my options now?
You can always opt for unchecked exceptions, that is sub-classes of RuntimeException class. These exceptions along with the sub-classes of Error are exempt from compile time checking.
Here Parent is defining throwException() method that does not have throws clause and the Child class overrides it but throws a new RuntimeException from the catch block.
class Parent{
public void throwException(){
System.out.println("Didn't throw");
}
}
class Child extends Parent{
#Override
public void throwException(){
try{
throw new ArithmeticException("Some arithmetic fail");
}catch(ArithmeticException ae){
throw new RuntimeException(ae.getMessage(), ae);
}
}
}

How to handle Exception properly from a method?

Suppose, I have a method:
private void someMethod() {
try {
//Do something here
}
catch (NullPointerException ex) {
System.out.println("error");
}
}
Now, I want to use this method somewhere else:
private void newMethod() {
someMethod();
JOptionPane.showMessageDialog(null, "Exception didn't occur");
}
Now, I want that if exception occurs in someMethod(), then newMethod() will not advance further, I mean, the JOptionPane message will not be shown in this case.
What will be the best way to do that? I have found a way by throwing another NullPointerException in catch block of someMethod() and then handling that from newMethod(). The code below demonstrates that:
private void someMethod() {
try {
//Do something here
}
catch (NullPointerException ex) {
System.out.println("error");
throw new NullPointerException("error");
}
}
private void newMethod() {
try {
someMethod();
JOptionPane.showMessageDialog(null, "Exception didn't occur");
}
catch (NullPointerException ex) {
System.out.println("error");
}
}
But, by this method, I am facing some difficulties for other cases. I guess there are better ways to achieve that. Thanks anyway.
You don't need to handle the exception inside someMethod. Instead you can declare the exception in this method's throws clause (if it is a checked exception) and let newMethod handle it.
private void someMethod() throws SomeCheckedException {
//Do something here
}
In case of NullPointerException, you don't need to do above, as it is an unchecked exception. Don't catch it inside someMethod, instead have try-catch inside newMethod.
It is good practice if your function intend to throw exception make it part of function declaration. So recommendation is to change someMethod() to private void someMethod() throws <exception Name>.
Depends on your requirement you can handle the exception in same method and throw another exception, or re throw same exception and handle it in another function.
In case you are re-throwing the same exception syntax is as follows:
private void someMethod() throws WhateverException {
try {
//Do something here
}
catch (WhateverException e) {
throw e;
}
}

Throwing Exceptions from Exception class in java

Ok ... So I am learning about exceptions in java and i am currently at throw statements. I throw an exception of Exception class, and then re-throw it from the catch block again to handle it in the main function. But whenever i throw it as Exception class, i always get an Error in the catch block(where i re-throw it to be handled in main).But as soon as i change the thrown and caught Exceptions to some particular Exceptions like NullPointerException, it works!
Error Code:
class ThrowingExceptions {
static boolean enable3dRendering = false;
public static void main(String [] com) {
try {
renderWorld();
}
catch(Exception e) {
System.out.println("Rendering in 2d.");
}
}
static void renderWorld() {
try{
if(!enable3dRendering) {
System.out.println("3d rendering is disabled. Enable 3d mode to render.");
throw new Exception("3d mode Disabled.");
}
else {
System.out.println("The World is Empty!");
}
}
catch(Exception e) {
System.out.println("Please handle the error");
throw e; // It gives me an error here
}
}
}
Working Code:
class ThrowingExceptions {
static boolean enable3dRendering = false;
public static void main(String [] com) {
try {
renderWorld();
}
catch(NullPointerException e) {
System.out.println("Rendering in 2d.");
}
}
static void renderWorld() {
try{
if(!enable3dRendering) {
System.out.println("3d rendering is disabled. Enable 3d mode to render.");
throw new NullPointerException("3d mode Disabled.");
}
else {
System.out.println("The World is Empty!");
}
}
catch(NullPointerException e) {
System.out.println("Please handle the error");
throw e;
}
}
}
Why doesn't it work with Exception class and worked with its subclass??
Note :- The error i get in the error code is Unhandled exception type Exception
Runtime exceptions extend RuntimeException. They don’t have to be handled or declared.
They can be thrown by the programmer or by the JVM.
Checked exceptions have Exception in their hierarchy but not RuntimeException. They
must be handled or declared. They can be thrown by the programmer or by the JVM.
Errors extend the Error class. They are thrown by the JVM and should not be handled or
declared.
When method throws checked exception (1) you should handle or rethow it.
When method throws uncheked exception (2) you can handle or rethrow it, but it's not obligatory.
But whenever i throw it as Exception class, i always get an Error in
the catch block(where i re-throw it to be handled in main)
It means that your method is throwing checked exception which should be handled or rethrowed.
Handling:
public class Main {
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
try {
throw new Exception();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
Rethrowing:
public class Main {
public static void main(String[] args) throws Exception {
try {
throw new Exception();
} catch (Exception e) {
throw new Exception();
}
}
}
In your case:
// You declaring that the caller should handle exception
static void renderWorld() throws Exception {
try {
if(!enable3dRendering) {
System.out.println("3d rendering is disabled. Enable 3d mode to render.");
throw new Exception("3d mode Disabled.");
} else {
System.out.println("The World is Empty!");
}
} catch(Exception e) {
System.out.println("Please handle the error");
// You cannot just throw uncheked exception here
// You should handle it yourself or a caller should do it
throw e;
}
}
Changing
static void renderWorld() { ... }
to
static void renderWorld() throws Exception { ... }
should fix this. This is for the reason that runtime exception are unchecked exceptions.
Would recommend you to read about the Checked and Unchecked exception in details here - Java: checked vs unchecked exception explanation.
It's because they are several Exception classes which are inherited from the class Exception. Each can be throwed, catched but they divide into two groups:
Checked and unchecked exceptions:
An unchecked exception doesn't need to be handled and the
NullPointerException which you tried is from that group, so you don't need to care about it technically.
A checked exception need to be handled every time or it won't
compile, these exceptions are like IOException.
Since the base Exception Object can be checked and unchecked as well the compiler cares about that it should be handled everytime.
If you give it a try and change the NullPointerException to IOException it won't compile either cause it is a Checked Exception. So it was just random, that you exactly find one type of Exception which your code can be work without compile error.
For more info visit my blog post about it:
http://www.zoltanraffai.com/blog/?p=93

compilation error while throwing exception?

What is wrong with this code?
public class Mocker<T extends Exception> {
private void pleaseThrow(final Exception t) throws T{
throw (T)t;
}
public static void main(String[] args) {
try{
new Mocker<RuntimeException>().pleaseThrow(new SQLException());
}
catch (final SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
As in pleaseThrow method throws SQLException still it gives Compilation error.
Error :
Unreachable catch block for SQLException. This exception is never thrown from the try
statement body
The problem is because you are throwing a RuntimeException, but trying to catch SQLException.
In your method,
private void pleaseThrow(final Exception t) throws T{
throw (T)t;
}
You are casting the argument SQLException in your case to T (which is RuntimeException in your case and throwing it.
So, the compiler is expecting a RuntimeException to be thrown and not SQLException.
Hope this is clear.
you would be able to write this when your pleaseThrowmethod actually throws SQLException.
Currently what you are doing is just passing a object of type SQlExcetion as parameter to this method.
Currently what Compiler observes is you are calling a method and it does not throw any SQLException , so compiler deems the catch clause as a problem and shows this compilation problem
Your pleaseThrow() does not throw an SQLException. You have some choices: make your catch to catch a generic Exception
catch (final Exception e) {
// TODO: handle exception
e.printStackTrace();
}
or make pleaseThrow(..) actually throw an SQLException
private void pleaseThrow(final Exception t) throws SQLException{
throw (SQLException)t;
}
or actually throw an SQLException
new Mocker<SQLException>().pleaseThrow(new SQLException());

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

Categories

Resources