Run a program without Try/Catch block - java

I'm making a sort of chat program in Java. Specifically, if I ask "can you open chrome?", the program will reply with "yes..." and then opens Google Chrome (Windows).
I have created the path to the Chrome as a string:
Runtime rt = Runtime.getRuntime()
String file="C:\\Program Files (x86)\\Google\\Chrome\\Application\\Chrome.exe";
I try to call the String, but says to either "Surround Statement with try/catch" or "Surround block with try/catch". Or the "Add throws clause to the "java.io.IOException" ".
myVocab.addPhrase("Can you open Chrome?", "Yes, one moment..." + rt.exec(file));
Whenever I do either of these, Chrome just opens automatically.
I'm somewhat new to Java so please tell me if there's an easier way to do this, or if I'm doing this completely wrong.

Some java functions need to be implemented with the try catch statements because it is possible to get an exception inside that function. An exception is defined as "An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions" more info
So, to manage an exception, for your case, you could:
try { code1 } catch (ExceptionType name) { code2 }
where ExceptionType should correspond to the possible error type your code1 could give you.
Ex:
try { //code to open google } catch (InterruptedException e) { e.printStackTrace(); }
e.printStackTrace(); will print error details

Related

Is there a way for me to throw an exception without it printing the stack trace?

The goal is to be able to do:
throw new RuntimeException();
without it printing:
Exception in thread "main" java.util.RuntimeException
at grame.GrameManager.add(GrameManager.java:40)
at grame.GrameManager.add(GrameManager.java:47)
at grame.Entity.<init>(Entity.java:56)
at grame.Entity.<init>(Entity.java:28)
at test.Test.main(Test.java:20)
(for example).
Is this possible? If so, how would I go about doing this?
Since exceptions are important, you could use a logging mechanism like log4j (http://logging.apache.org/log4j/1.2/) and set the logging to a different level when you don't want some exceptions to be printed or log to a file instead of console for example.
If you just don't care about the exception, catch it and do nothing with it (empty catch, which is awful).
You can redirect System.err by setting System.setErr(null);
No thrown exception ever directly generates a stacktrace to the error console. It's up to the code who is calling it to do so. In the case of a main program:
public static void main(String args[]) throws Exception {
// do something that throws an exception
}
If you don't catch the exception, the system will actually spit it out to the console i believe.
Somewhere along the way, you need to deal with the exception. If showing it in the GUI is what you want, then you'll have to do something like this:
public interface ExceptionHandler {
void handleException(Exception e);
}
public static void main(String args[]) {
ExceptionHandler exceptionHandler = ...;
try {
// something that might throw an exception
}
catch (Exception e) {
exceptionHandler.handle(e);
}
}
Just catch the exception, and don't put anything in the catch block.
I should add that doing this is generally a bad idea. Having that stack trace, or some sort of message is very useful when finding out what went wrong in your program.
If you want the method to kill the program without printing a stack trace, place it in a try/catch block, and under catch simply use the statement:
System.exit(1)
This lets the system know that the program exited with an irregular (non-zero) state, but does not print anything to System.err.
All that you really need to do is catch it... However, this is a really bad idea. You may want to make your own exception and catch that. This way you will not swallow exceptions that you should not be ignoring. The only time that you should really consider to do this, is if you cannot allow your application to blow up. If that is the case then you should at the very least log the error.
This explains it better than I can (and is a good resource regardless). Basically, it suggests that:
"If a client can reasonably be expected to recover from an exception,
make it a
checked exception. If a client cannot do anything to recover from the exception,
make it an unchecked exception".
Like this:
try {
some code...
} catch (RuntimeException e) {
}
1. Java compiler only cares during compilation that you have given a catch for a try, whether you implement any code in the catch or not.
2. You can keep the catch block empty, or print it on the console, log it..etc....
eg:
try{
}catch(Exception ex){
}
3. But printStackTrace() prints the method name, class name , file name and the line number where the exception has occurred.

Handle the Exception and Continue the process without termination in java

I am working on java, I read huge no.of XML files & insert them into ORACLE database but while inserting I am getting Exception, Then my program terminates without processing remaining records, Could any one please help me out from this situation, I want to read the files until unless they finished without termination of program while exception occurs.
for (File f : myFileArray) { //Or whatever you have
try {
// your code which might throw exception
} catch ( <Your exception name here> e) {
System.err.println("File failed: " + f.getAbsoultePath() );
continue; //if more code follows the try catch block, otherwise omit it
}
}
Since you did not gave any code snippet for what you actually do, I tried a guess.
As the comments suggest, you use try/catch-Blocks for handling exceptions in Java.
A good tutorial is imho
http://chortle.ccsu.edu/java5/index.html
Chapter 80 and 81.

Prevent NoClassDefFoundError from crashing program

I'm writing a Java program for my work-study program which relies on the RXTX serial drivers. It is running well on my testing machines, however I have noticed that when run on a machine that does not have RXTX installed the application fails to open. In the console it has thrown the "java.lang.NoClassDefFoundError" exception for "gnu/io/CommPortIdentifier". I put this into a try/catch so that it would instead display a message to the user telling them to check their RXTX driver installation rather than simply exiting the program. However it doesn't actually do this, still just closes out as soon as it hits that line. Any ideas? Thanks!
EDIT: Some code for ya:
Enumeration sportsAll = null;
Vector<String> v = new Vector();
SerialPort sp;
CommPortIdentifier portID;
String currString;
try {
sportsAll= CommPortIdentifier.getPortIdentifiers();
} catch (Exception e) {
v.addElement("Check RXTX Drivers");
}
The "sportsAll= CommPortIdentifier" line is the one that throws the error
It's because you try to catch Exception which is not a parent class for NoClassDefFoundError see JavaDoc. Catch the concrete exception class instead.
Better approach is to check for availability of the driver itself. For example:
private static boolean isDriverAvailable() {
boolean driverAvailable = true;
try {
// Load any class that should be present if driver's available
Class.forName("gnu.io.CommPortIdentifier");
} catch (ClassNotFoundException e) {
// Driver is not available
driverAvailable = false;
}
return driverAvailable;
}
java.lang.Error states
An Error is a subclass of Throwable
that indicates serious problems that a
reasonable application should not
try to catch. Most such errors are
abnormal conditions.
And java.lang.NoClassDefFoundError extends LinkageError (which extends Error). You shouldn't catch any Error at all in a try-catch block.
You will have to write a code to check if RXTX is installed first before executing your rest of the code.
This is because NoClassDefFoundError extends Error (not Exception).
The best way would be to catch NoClassDefFoundError itself. You can also catch either Error or Throwable.

How to retry opening a properties file in Java

I'm trying to handle an FileNotFoundException in Java by suspending the thread for x seconds and rereading the file. The idea behind this is to edit properties during runtime.
The problem is that the programm simply terminates. Any idea how to realize this solution?
There's a good-old recipe, originally by Bjarne Stroustroup for C++, ported here to Java:
Result tryOpenFile(File f) {
while (true) {
try {
// try to open the file
return result; // or break
} catch (FileNotFoundException e) {
// try to recover, wait, whatever
}
}
}
Do the file loading in a loop and set the variable the condition depends on after the file has been successfully read. Use a try-catch block inside the loop and do the waiting in the catch-block.
Some code snippets would be useful, but one of the following could be the problem:
Your code successfully catches the first FileNotFoundException but after waking up the code does not successfully handle a second one
Another exception is being thrown which is not being handled. Try temporarily wrapping the code in question with a catch (Exception e) to see what exception is being thrown
The program you use to edit the file is 'locking' the properties file and possbily preventing access by your Java code.
Good luck
If the Exception is never caught, the thread is terminated. If this is your main thread, the application ends. Try the following:
try
{
props.load(...);
}
catch (FileNotFoundException ex)
{
Thread.sleep(x * 1000);
props.load(...);
}

Calling a Java main function

I am trying to call another JAR's main function. Now, this main function is enclosed under a try and catch block.
But when the main call returns a "NullPointerException" the program just crashes instead of catching it.
So, for example
try {
somelibary.main()
}
catch (Exception e) {
System.out.println("Exception Caught");
}
This code dosent catch NullPointerException from the main().
Does anyone know the reason y?
Your code, as shown, will definitely catch a NullPointerException thrown by somelibrary.main(). If the application stops anyway due to a NullPointerException there's a fair chance that somelibrary at some point catches the exception, dumps a stack trace and calls system.exit()
In that case the question is not how to catch a NPE, but how to prevent System.exit() from actually exitting.
And the answer to that question can, of course, be found on StackOverflow to, right here. Just install a SecurityManager before the call to someLibrary, and reset the securityManager afterwards.
It's possible that the other main function is doing its own error handling, à la
public static void main(String[] args) {
try {
....
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
If that's what the other main function is doing, then you won't be able to catch its exceptions. Do you have the code for this main function?
With the code you are showing, you will catch also the NullPointerException. But the execution will go on after the catch-block. So the execution of somelibary.main() is stopped in this case. If your main() is not contain more code, the program will end after catching the exception. That's what likely happens. You could post the complete code of your main, to verify this.
Addition: You want to know how to go on with the execution of the program. But in this case somelibrary.main() is stopped by throwing the exception. The only option in the main-class will be a loop, that reexecutes somelibrary.main(). The other possibility is to catch the Exception at some higher level (main input-loop) where you can ignore the problem and go on with the execution of the code. As you say you execute another jars-main I suspect you cannot change the code of the other jar. So you are only left with reexecute the other main:
boolean ended = false;
while (!ended)
{
try {
somelibary.main()
ended = true;
}
catch (Exception e) {
System.out.println("Exception Caught");
}
}
This code restarts the other main on an exception but ends if the other main ends normally.
Perhaps you could execute the main method in another process using Runtime.exec, then capture the result or the error from out/err stream.

Categories