IF and ELSE in TRY CATCH? - java

I have this code
root = new Root();
root.checkRootMethod2();
TextView=(TextView)view.findViewById(R.id.textView4);
if(root.checkRootMethod2()) {
TextView.setText(Html.fromHtml("<b>TEXT 01</b><br>"));
} else {
TextView.setText(Html.fromHtml("<b>TEXT 02</b><br>"));
}
try {
if (root.RootAvailibility() && (root.checkRootMethod3())) {
try {
Process process = Runtime.getRuntime().exec("su");
OutputStream stdin = process.getOutputStream();
stdin.flush();
stdin.close();
} catch(Exception e) {
}
TextView.append(Html.fromHtml(
"<b><font color=\"green\">TEXT 03</b></font>"));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
root.busybox();
TextView.append(Html.fromHtml(
"<br><b><font color=\"green\">TEXT 04</b></font>"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e) {
TextView.append(Html.fromHtml(
"<br><b><font color=\"red\">TEXT05</b></font>"));
}
I wish that if if (root.RootAvailibility() && (root.checkRootMethod3())) return true Viewing a TextView that says something.If return false, another TextView that displays something else. As happens for root.checkRootMethod2 (); Same goes for root.busybox (); Do you have any idea on how I can do? Now visualize always Text04

try {
if (root.RootAvailibility() && (root.checkRootMethod3()))
{
try
{
/// your code ...
}
catch(Exception e){ }
TextView.append(Html.fromHtml("<b><font color=\"green\">TEXT 03</b></font>"));
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Codes here runs always regardless of if clause.
the code (try block in your case) runs regardless of the if condition as the try block clears the scope of if block.
Either put try completely inside if block or surround both if,else statement by a single try block.

I don't know what is the need of multiple try/catch here :
try {
if (root.RootAvailibility() && (root.checkRootMethod3()))
{
try
{
You can add one more catch(Exception e) to the upper try/catch block and that will serve the same purpose.
Secondly there is no else part to this if (root.RootAvailibility() && (root.checkRootMethod3())). So, if it is false the program will simply move forward.

Well you're always going to see Text04 because there's no conditional that excludes it. The try catch block it's in is at the top level.
It would help if you could provide a short, self-contained, compilable example of your code. There's clearly other potentially relevant code missing. For example, the try that goes with that last catch block. Also, it might help you to comment the beginning and end of your code blocks so that you can tell what's included in the if else statements.

Related

calling catch block from a method when an exception occured in try block

Is it any possible way there to write catch block inside a method and call it from finally when an exception occured in try block
Ex:
try
{
int a=0,b=0;
a=b/0;
}
finally
{
callExceptions();
}
}
public static void callExceptions()
{
catch(Exception e)
{
System.out.println(e);
}
}
catch block must follow a try block. It can't stand alone.
And finally block are made to be after the catch.
You wrote an alone catch inside a finally. That doesn't make sense.
The easiest solution is to pass the exception to the method as a parameter:
public static myMethod() {
try
{
int a=0,b=0;
a=b/0;
}
catch (Exception e)
{
callExceptions(e);
}
finally
{
// do what ever you want or remove this block
}
}
public static void callExceptions(Exception e)
{
System.out.println(e);
}
Ways to uses try/catch/finally
1.- when you want to try to use some method, if everything goes well, will continue else one exception will be thrown on catch block.
try {
// some method or logic that might throw some exception.
} catch (ExceptionType name) {
// catch the exception that was thrown.
}
2.- It's the same the first but adding finally block means that the finally block will always be executed independently if some unexpected exception occurs.
try {
// some method or logic that might throw some exception.
} catch (ExceptionType name) {
// catch the exception that was thrown.
} finally {
// some logic after try or catch blocks.
}
3.- try and finally blocks are used to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. For example:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
Referencias Official documentation JAVA for try/catch/finally blocks
On your case:
public static myMethod() {
try {
int a=0,b=0;
a=b/0;
} catch (Exception e) {
callException(e);
}
}
public static void callException(Exception e) {
System.out.println(e);
}
This was too long for a comment so sorry it's not a direct answer to your question (as others have pointed out, that's not possible). Assuming what you're trying to do is define a common way to handle your exception logic in one place, Callable might be a way to go. Something like the following might suffice... Although I'm not going to comment on whether any of it is a good idea...
static E callAndHandle(final Callable<E> callable) {
try {
return callable.call();
} catch (final Exception ex) {
System.out.println(ex);
return null;
}
}
static void tryIt() {
final String result = callAndHandle(() -> {
// Thing which might throw an Exception
return "ok";
});
// result == null => there was an error here...
}
Unfortunately Runnable doesn't declare any Exception in the signature, so if you know it always needs to be void and you don't like the return null; or similar hacks, you'd have to define your own interface to pass in.

JMeter does not execute Java code correctly if it's ran as .jar file from command line

I'm designing JMeter scenario which implies executing a certain .jar file via OS Process Sampler element. My Java code has while loop which basically checks a certain mailbox for a letter with a certain subject. Loop waits until finds one (emails are always delivered with roughly 3 minutes delay), parses it and writes some data to .txt file.
If I run this .jar directly from cmd then the code works as expected. But if I run it via JMeter OS Process Sampler then it never creates a file for me. I do see that email is delivered to inbox, so expect it to be parsed and .txt created.
At first I suspected that JMeter finishes Java scenario without waiting for while loop to execute. Then I put OS Process Sampler in a separate Thread and added a huge delay for this thread in order to wait and make 100% sure that email is delivered and Java only need to parse it but it does not help.
View Results Tree never shows any errors.
Here is my OS Process Sampler: https://www.screencast.com/t/LomYGShJHAkS
This is what I execute via cmd and it works as expected: java -jar mailosaurJavaRun.jar email533.druzey1a#mailosaur.in
And here is my code (it does not looks good but it works):
public class Run {
public static void main(String[] args) {
MailosaurHelper ms = new MailosaurHelper();
String arg1 = ms.getFirstLinkInEmail(args[0]);
BufferedWriter output = null;
try {
File file = new File("url.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(arg1);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class MailosaurHelper {
protected final String API_KEY = "b3e4d2b193b5eb2";
protected final String MAILBOX_ID = "d1uzey1a";
public MailboxApi getEmailBox() {
return new MailboxApi(MAILBOX_ID, API_KEY);
}
public String getFirstLinkInEmail(String email) {
MailosaurHelper ms = new MailosaurHelper();
String link = "";
if (link.equals("") || link.isEmpty()) {
try {
Thread.sleep(3000);
link = ms.getAllEmailsByReceipent(email)[0].html.links[0]
.toString();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return link;
}
public Email[] getAllEmailsByReceipent(String recepient) {
try {
int ifArrayIsEmpty = getEmailBox().getEmailsByRecipient(recepient).length;
while (ifArrayIsEmpty == 0) {
try {
Thread.sleep(3000);
ifArrayIsEmpty = getEmailBox().getEmailsByRecipient(
recepient).length;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (MailosaurException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Email[] listOfEmails = null;
try {
listOfEmails = getEmailBox().getEmailsByRecipient(recepient);
} catch (MailosaurException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listOfEmails;
}
The bottom line is that I need to parse Mailosaur email, retrieve URL from it and use it further. Any other suggestion on how to do that using Jmeter/Java/Mailosaur are appreciated.
You don't need cmd in here, but if you're adamant to stick with it - use /C key when you call it.
Then, are your sure you're looking for your file in the right place?
According to documentation:
By default the classes in the java.io package always resolve relative
pathnames against the current user directory. This directory is named
by the system property user.dir, and is typically the directory in
which the Java virtual machine was invoked.
Check it thoroughly, BTW - you should see it in your sampler result.

java.nio.SocketChannel always returning the same data

could you please have a look at my code :
private void initSocket() {
try {
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.bind(null);
socketChannel.connect(new InetSocketAddress(host,port));
while(! socketChannel.finishConnect() ){
Thread.sleep(5);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void initOutput() {
outBuffer = ByteBuffer.allocateDirect(512); //Allocate direct for better performance (no java-heap alloc)
outBuffer.clear();
}
private void initInput() {
inBuffer = ByteBuffer.allocateDirect(1024); //Allocate direct for better performance (no java-heap alloc)
inBuffer.clear();
}
public String in () {
try {
while (socketChannel.re)
socketChannel.read(inBuffer);
inBuffer.mark();
final String ret = Charset.forName("UTF-8").newDecoder().decode(inBuffer).toString();
bulletin.PIPE_IN.Info.push(" <<< ", new String[]{"TsPipe2","in"}, new Object[]{ret, inBuffer});
return ret;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void out (String out) {
outBuffer.clear();
outBuffer.put(out.getBytes());
//Write all in one go
bulletin.PIPE_OUT.Info.push(" >>> ", new String[]{"TsPipe2","out"}, new Object[]{outBuffer, out});
int toWrite = outBuffer.remaining();
for (int i = 0; i < toWrite; ++i) {
try {
i += socketChannel.write(outBuffer);
Thread.sleep(Period.NIO_CHANNEL_WRITE_SLEEP.getValue());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
And tell me what am I doing wrong ?
As the topic states I am always getting the same data from the in-method and am not sure wether my out-method works or not
I travelled throught several tutorials now and it might be I mixed something up.
I also found promising stuff on stackoverflow - but nothing ever worked.
As a little background info - I am writing a Teamspeak bot communicatin via Sockets with a TS-Server and have gone pretty far. From the moment I first heard about nio I wanted to migrate to it.
Are their other frameworks to consider ? heard Google Grizzly is pretty neat, but not sure if it's useful for my case ?
I believe you're missing some braces at this while (socketChannel.re) loop.

How put string to Shared Preference?

Could anybody help me, please? I have this code:
Process a;
try {
a = Runtime.getRuntime().exec("su");
DataOutputStream swp = new DataOutputStream(a.getOutputStream());
swp.writeBytes("cat /proc/sys/vm/blabla\n");
swp.writeBytes("exit\n");
swp.flush();
try {
a.waitFor();
if (a.exitValue() != 255) {
// TODO Code to run on success
toastMessage("root");
}
else {
// TODO Code to run on unsuccessful
toastMessage("not root");
}
} catch (InterruptedException e) {
// TODO Code to run in interrupted exception
toastMessage("not root");
}
} catch (IOException e) {
// TODO Code to run in input/output exception
toastMessage("not root");
}
This code swp.writeBytes("cat /proc/sys/vm/blabla\n"); copies text (string) from system file called "blabla". And then I need to put this text (String) to my SharedPreferences. How can I achieve it?
If this was your code, you should know. In case you don't, you can follow the Tutorial.
In your case, you'll want to use the putString()-method.
To get what cat printed out, you'll need the output of your Process-object. Use the getInputStream()-method.

Saving a singleton object

I know this site isn't made for questions like this but I've been searching for the answer to this I haven't found anything and I need a confirmations.
I have a singleton class which is the centre of my program, in some situations I try to save its state, however it seems it doesn't save properly, and I don't see why because It's not the first time I do this, however It is the first time I try to save a singleton, so is it possible to save a singleton object?
Here are my loading and saving codes of this object
public void Loading(String name) {
ObjectInputStream is = null;
//ignore this variable
game_loaded = 1;
try {
is = new ObjectInputStream(new FileInputStream(name + ".dat"));
//Logica is the singleton class,
//logi is the name of the variable where it is
logi = (Logica) is.readObject();
} catch (FileNotFoundException e1) {
JOptionPane.showOptionDialog(frame, "Game Invalid", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
return;
} catch (IOException e1) {
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
JOptionPane.showOptionDialog(frame, "Game Loaded Sucessfully", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
}
Save:
public void saving(String nome){
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream(nome+".dat"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return;
} catch (IOException e) {
// TODO Auto-generated catch block
return;
}
try {
os.writeObject(Logica.getLogica(null));
} catch (IOException e) {
// TODO Auto-generated catch block
return;
}
JOptionPane.showOptionDialog(frame, "Game Saved sucessfully", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
if (os != null)
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EDIT
Ok I may have explained corretcly, it doesn't give me any error loading, however it doesn't load the state I saved, it loads an new "Logica" as if I had created a new one
There's nothing about Singleton per se that says it can't be serialized; you can write incorrect serialization code for any class. It's not clear what's wrong, and I'm not willing to pore over your code to figure it out, but it should be possible to do.
You have an empty catch block for IOException. That's always a bad idea. You've swallowed the exception that might explain everything. Print the stack trace.
The situation you have described is not possible. Ergo you haven't described it correctly. Probably there is something wrong with your observations.
I strongly suspect an IOException or FileNotFoundException, despite your comment in another answer. You have posted code that ignores exceptions in at least four separate places. The presumption is overwhelming.
In fact your exception handling needs a lot of work. You aren't closing the file in case of exceptions for example. There are no finally blocks. You have multiple try/catch blocks where you should have one try and several catches.
Further questions along other lines of enquiry. Is the file being created? With non-zero length? Or else maybe the singleton class only has transient fields?

Categories