Need to move from try block to catch - android

I have written some code in the try block as follows.
try {
if (server1IPAddress != "") {
if ( InetAddress.getByName(server1IPAddress).isReachable(1000) == false) {
}
InsertUploadedTrancasctionDetails(server1IPAddress, deviceId,
XMLTransactionData);
}
} catch (Exception exception) {
if ((server1IPAddress != server2IPAddress)
&& (server2IPAddress != "")) {
InsertUploadedTrancasctionDetails(server2IPAddress, deviceId,
XMLTransactionData);
}
when we are not able to reach an IP Address i need to move from try block if condtion to catch block ie when IP address reachable is false.
if ( InetAddress.getByName(server1IPAddress).isReachable(1000) == false) {
}
I am not able to make an exception in the if block.
Is there any way to move from the If block to the catch block without making an exception or by making an exception in the if block.
Will any one help me please.

If the code for the not-reachable condition is the same as the code in the exception block, then you should either throw an exception, or refactor the current catch code into a method, and call that method from both locations. (Or just repeat the code, but ew.) I'm not really sure what the problem is.
FWIW, checking explicitly against false is generally frowned upon--negate the condition instead:
if (!InetAddress.getByName(server1IPAddress).isReachable(1000)) {
// Call refactored catch-handling code, or throw exception.
}
Catching Exception, particularly if not logging it, is an anti-pattern, although if you're wrapping it and/or re-throwing it, it's not as bad.

Related

How to handle errors in BlockingObservable without subscribe()?

for various reasons I have to block on observable like this
Foo foo = fooBarNetworkRequestObservable()
.toBlocking()
.single();
return foo;
But how do I handle errors now? Is is possible without subscribe(new Subscriber .. onError()?. I tried wrapping the code in try-catch but compiler complains that IOException is never thrown in coresponding try-catch block. Any solutions? Thanks
You are in blocking world so you need try-catch. Since the API can't throw checked exceptions, we wrap them into RuntimeException for you:
try {
source.toBlocking.single();
} catch (RuntimeException ex) {
if (ex.getCause() instanceof IOException) {
// handle IOException
} else {
throw ex; // something other happened
}
}

smack error when trying to login on server

public void login() {
try {
connection.login(loginUser, passwordUser);
Log.i("LOGIN", "Yey! We're connected to the XMPP server!");
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
Log.i("login fuction","login error");
e.printStackTrace();
}
}
[eclipse error log]
I'm getting an error at this stage after successful connection to the server
i don't have the privilege to comment but from the input that you have given here the error possibly lies in the login function that is throwing the null point exception
Possible cases
1) When you call instance method on a null object. you won't get null pointer exception if you call static method or class method on null object because static method doesn't require an instance to call any method.
2) While accessing or changing any variable or field on null object.
3) Throwing null when an Exception is expected to throw.
4) When calling length of array when array is null.
5) Accessing or changing slots of null just like an array.
6) When you try to synchronize on null object or using null inside synchronized block in Java
give the code for login function for further help
Hope this helps you
Which server are you calling? If you are calling gtalk or fchat, those have stopped using xmpp. You may search in Google to find out. And if you plan to connect to you own ip server, please use xmpptc. It would be nice if you could give some more of your code.
I've finally found the solution, i had to add smack-java7 in my dependencies

Is it safe to implement business logic inside a catch block?

I want to update a shared preference and ImageView(using setImageResource) inside a catch block. But is is safe to do so?
try{
//do something
} catch (Exception e) [
Log.d("TAG", "Exception " + e);
sharedPref.edit().putString("Value", "no_value").apply();
myimageview.setImageResource(resid);
}
It's ok to do that. Actually there is no another way to execute code when some exception happen. Of course it is better if you know the type of exception (for example null pointer) and to use something like:
if(something != null){
// normal logic
}else{
// exception logic
}

Android: How to check condition with async task return value

I am doing some processing in async task to check some values on server if the value present server php script returns true otherwise false.
everything is working fine, but whenever i am trying to check condition with the http response string the condition never gets checked..
partial code:
CheckDevice cd = new CheckDevice();
String chk[] = new String[1];
chk[0] = di.imei;
try {
cd.execute(chk).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
cd.getFinalResult(); //This returns string "true" (working outside if);
if(cd.getFinalResult == "true"){
//This loop never executes... why?
regButton.setEnabled(false);
regButton.setText("Device Already Registered");
Toast.makeText(getApplicationContext(), cd.getFinalResult(), Toast.LENGTH_LONG).show();
}
What is the problem? someone please tell...
Do,
cd.getFinalResult().equals("true") //OR
cd.getFinalResult().equalsIgnoreCase("true")
as you cannot compare strings using ( == ).
Check this for details.

android exception for validating file exist not working

I've been working with Eclipse ADT for about 2 months. In that time, I have a small utility that allows me to select an IP Address and Port, and then send a file to that combo. The utility works as intended, but when I type in the wrong file name, the application hangs.
#Override
public void run() {
if (data != null) {
this.send(data);
} else if (this.file != null) {
if (file.exists()) {
this.send(file);
} else {
transferError = new FileNotFoundException("The specified file could not be found");
}
}
}
I've even tried to do the following in hopes that one or the other would throw, but I am unsuccessful in both.
public void run() {
if (data != null) {
this.send(data);
} else if (this.file != null) {
if (file.exists()) {
this.send(file);
} else {
transferError = new FileNotFoundException("The specified file could not be found");
}
}try {
throw new Exception("blah blah blah");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I've jockeyed around the exception, I've added the one above, I've tried placing it in different places, and all unsuccessful. Again, I'm exceptionally new to this, and got here from basically mincing various tcp client codes. Aside of creating a way to throw the exception correctly, please help me understand why the first one isn't working and why the one you suggest is.
in your else block you aren't throwin the transferError you create.
throw transferError;
However you probably won't be able to do that because FileNotFoundException is a checked exception and the run() method doesn't declare any thrown exceptions. You probably need to find a different way to present the error to the user, like with a Toast or something.
Your second block doesn't work because you are catching the exception you throw.

Categories

Resources