Suppose in your program you might get an IndexOutOfBoundsException. i am handling it in the following way:
try{
//throws an IndexOutOfBoundsException during runtime
}catch(IndexOutOfBoundsException ex){
System.err.println(ex);
}
This will only display java.lang.IndexOutOfBoundsException. But I would like to display a detailed error message (which won't terminate the program), like the one that java gives us (lineNumber, fileName, etc) when we do not handle the error and thus terminates the program.
In Java you can use printStackTrace on any exception object to get the stack trace printed by Java. In your case a minimal:
try {
// Throw an IndexOutOfBoundsException
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
}
This prints the stack trace to System.err. You can also pass it a print stream or even System.out to print to that particular stream.
Additionally, if you use java logger, you can use:
logger.log(<LOG_LEVEL>, <LOG_MESSAGE>, ex);
to log the exception. For more details see: https://docs.oracle.com/javase/7/docs/api/java/util/logging/Logger.html
Use ex.printStackTrace() method to print the exception:
try {
int[] x = new int[1];
x[2] = 5;
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
}
System.err.println("Program completed successfully");
Demo.
If you are running in an environment where console output is not desirable, call ex.getStackTrace(), and display elements in a way that is consistent with the user interface of your program.
You can use
ex.GetMessage()
Thanks
Got this from one of my teachers. Might be helpful for other beginners like me.
(This is not a part of any h.w./assignment/etc. Curiosity.)
public class ExceptionDemo{
public static void main(String[] args){
int[] array = new int[2];
try {
System.out.println(array[100]);//non-existent
} catch (IndexOutOfBoundsException ex){
StackTraceElement[] e = ex.getStackTrace();
System.err.println("Got error= " + ex + "\n"+
"in file "+e[0].getFileName() +"\n"+
"in class "+e[0].getClassName() +"\n"+
"in method "+e[0].getMethodName() +"\n"+
"in line "+e[0].getLineNumber());
System.err.println("Full trace= ");
ex.printStackTrace(System.err);
}
System.out.println("As Salamu Alaikum");
}
}
Related
I want to find out the error line number using try and catch. I tried to get some information from How to get error line number of code using try-catch, but it didn't help since I use different language.
Now, I am getting java.lang.NumberFormatException: For input string: "" when I do
try {
// My Code Here
} catch(Exception e) {
System.out.println(e);
}
I tried printing e.getStackTrace()[0].getLineNumber()); as well, but it seems like it's not showing the correct error line number. Is there any way I can get it easily? I have a pretty big file and I don't think I'll be able to go over line by line to figure out what's wrong.
Thanks!
If you use a Logger library, it can print the stack trace in debug mode that points to the line number. else printStackTrace() is your friend.
try {
// My Code Here
} catch(Exception e) {
System.out.println(e);
e.printStackTrace(); // This will give line number
}
package com.ms.common;
public class Run {
public static void main(String[] args) {
try {
int value = 5;
int divider = 0;
int result = value / divider;
} catch (Exception e) {
System.out.println(e.getStackTrace()[0]);
}
}
}
Error at Run.java at line# 11
com.ms.common.Run.main(Run.java:11)
public static void main() {
String fileName = "cardNumbers.txt";
String line = null;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
CreditCard card = new CreditCard(line);
if (card.creditCardType().equalsIgnoreCase("Unknown"))
{
System.out.println("Card number " + card.getCardNumber() + "is an unknown credit card type.");
}
else if (card.isValid())
{
System.out.println(card.creditCardType() + " number" + card.getCardNumber() + " is valid.");
}
else if (!card.isValid())
{
System.out.println(card.creditCardType() + " number " + card.getCardNumber() + " is not valid.");
}
}
}
catch (FileNotFoundException ex)
{
System.out.println("file not found exception thrown");
}
catch (IOException ex)
{
System.out.println("error while reading the file");
}
finally
{
System.exit(0);
}
}
When I run this method it just says ProcessCardNumbers.main(); VM Terminated. Instead of actually printing out the content.
If I add a print at the very start of the function or in the finally block, they are printed.
Im not sure why this is happening or how I can fix it.
As you told us that:
Adding a println at the start is printed
and
Adding a println in the finally works too
we can deduce that your code is working. It's just that when you reach while((line = bufferedReader.readLine()) != null), line stays null, so you never enter your while.
Why is that? Well, your file may be empty to begin with. If it is not, double-check the encoding of your file: it may not be using the proper returns symbols, hence not having a "completed line".
This seems that in your text file cardNumbers.txt has no data. When this program will execute within while loop bufferedReader.readLine()). will return null. So loop will terminate. After termination you have written System.exit(0); function in finally block which terminate JVM on the spot. So JVM is terminated now that's why you are not able to see anything after working of this code.
If you want to check working, write one SOP statement in finally block. Probably that will execute without termination of JVM.
The problem here is not the bug in your code but the design problem that does not let you see the bug.
You are probably getting an undeclared exception (RuntimeException) and the VM can't print it because you kill it before in the finally.
You have several options:
Remove the System.exit(0); and let it die normally. This may fail if there is another non-daemon thread running. You may try to stop it. You can, for example, cancel a Timer.
Add a catch (RuntimeException e) { section before the finally and print the captured error. e.printStackTrace(); should do the trick.
With any of those you should see the exception on console so you can fix it.
Your main method signature must look like this:
public static void main(String[] args)
instead of
public static void main()
I am trying to make a program which allows the user to enter 2 integers (marks).
In case the user doesn't enter an integer, I am creating a try and catch code.
The problem is that after I try to enter letters instead of numbers, there is an error coming out but the program carries on, saying that I didn't pass. How do I let the program stop after saying to the user that he entered a wrong mark?
Here is my code:
public void actionPerformed(ActionEvent e)
try{
myCalculator.setCWK(Integer.parseInt(courseEnter));
myCalculator.setExam(Integer.parseInt(examEnter));
}
catch (Exception a){
System.out.print("System error");
}
displayArea.setText("" + myCalculator.calculateModuleMark());
if(myCalculator.hasPasssed()==true)
{
displayArea.setText(myCalculator.getModuleCode() + "Congratulations! You have PASSED! With a score of " + myCalculator.calculateModuleMark() + "%");
getContentPane().setBackground(Color.green);
}
else
{
displayArea.setText("I am sorry");
getContentPane().setBackground(Color.red);
}
}
If you want the program to "stop" after a certain statement, System.exit(0) is your friend. So, in your catch statement, you could have
catch (Exception a){
System.out.print("System error");
System.exit(0);
}
Note that this is different than return, as System.exit(0) will completely stop your program flow, not just this specific method.
After printing out an error simply type return.
The try...catch blocks means
if an error occurs in the try instruction block, execute the catch instruction block
In your case, you're not exiting the function in your catch block, so it will carry on.
Exception handling is essentially done to prevent the code from exiting abruptly without any error message.
You can just call System.exit(1) after System.out.print("System error").
Note: System.exit(0) means program terminated as expected while any other error code within bracket means there was an error.
So, now your code will be:
public void actionPerformed(ActionEvent e){
try{
myCalculator.setCWK(Integer.parseInt(courseEnter));
myCalculator.setExam(Integer.parseInt(examEnter));
}
catch (Exception a){
System.out.print("System error");
System.exit(1);
}
displayArea.setText("" + myCalculator.calculateModuleMark());
if(myCalculator.hasPasssed()==true)
{
displayArea.setText(myCalculator.getModuleCode() + "Congratulations! You have PASSED! With a score of " + myCalculator.calculateModuleMark() + "%");
getContentPane().setBackground(Color.green);
}
else
{
displayArea.setText("I am sorry");
getContentPane().setBackground(Color.red);
}
}
For some reason, I'm having problems sending output to a process that I've created in Java. The external process is running in a command prompt, and the peculiar thing is that I can click that, type, hit enter, and I'll get output from the program. It addition my program can read all the output coming from the program, it just can't send anything to it.
Anyways, here is the relevant code I'm using that just isn't working...
try {
ProcessBuilder builder=new ProcessBuilder(args);
builder.redirectErrorStream(true);
final Process p=builder.start();
// Process has been created and is running
try {
String b="";
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
final BufferedWriter output = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
new Thread(){public void run(){
// This thread will periodically send "get_time" to the process to get an update on its progress
while(true)
{
try {
Thread.sleep(1000);
p.exitValue();
// p.exitValue() only works when process has ended, so normal code goes in the catch block
output.close();
break;
// Leave the infinite loop if the program has closed
} catch (IOException ex) {
Logger.getLogger(OvMusicUI.class.getName()).log(Level.SEVERE, null, ex);
break;
// Leave the infinite loop if we tried closing our output stream, but it was already closed
} catch (InterruptedException ex) {
Logger.getLogger(OvMusicUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalThreadStateException e) {
try {
System.out.println("Outputted: get_time");
output.write("get_time" + System.lineSeparator());
output.flush();
// Give the process some input
} catch (IOException ex) {
Logger.getLogger(OvMusicUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}}.start();
while((b = input.readLine()) != null){
System.out.println(new Time(System.currentTimeMillis()).toString() + " " + b);
// Log all output the process gives
}
input.close();
} catch (IOException ex) {
Logger.getLogger(OvMusicUI.class.getName()).log(Level.SEVERE, null, ex);
}
// More code here
} catch (IOException ex) {
Logger.getLogger(OvMusicUI.class.getName()).log(Level.SEVERE, null, ex);
}
If necessary, I can give an example command and the name of the external program being run so you can try it yourself...
Thanks!
EDIT: Here is an example of what's passed into the ProcessBuilder: Arrays.asList("VLC\vlc.exe", "-Irc", "-vvv", "http://www.youtube.com/watch?v=xfeys7Jfnx8", "--sout", "file/ogg:Untitled 1.ogg", "--play-and-exit", "--rc-quiet"). The only difference is I use absolute paths instead of relative paths. The program is VLC Media Player 2.0.7.
Your code has a few problems. First, you generally should not use exceptions for your regular control flow: it's expensive, it's difficult to read, and it makes handling actual errors more difficult. It's generally better to spawn another Thread that calls p.waitFor() and signals your main thread to complete, such as with wait/notify.
Also, your construction with the infinite loop and using break instead of return will make your code more difficult to debug; instead, use a Timer.
It looks like the output to your external program probably is working correctly but that the problem is just with reading its output. The program may be buffering its own output or may be detecting that it's not being run interactively and behaving differently.
There are a few similar questions, but for C# mostly.
#Override
public void setExtraItemsDone(XMPPResourceConnection session) throws NotAuthorizedException
{
try
{
cp1 = Calendar.getInstance().getTimeInMillis();
try
{
...
} catch (TigaseDBException e) {
...
} catch (UnsupportedOperationException e) {
...
}
} catch (Exception e) {
cp2 = Calendar.getInstance().getTimeInMillis();
throw new NotAuthorizedException(e.getMessage() + "; method took " + (cp2 - cp1) + " ms", e);
}
I am basically looking to catch a MySQLTimeoutException and turn it into a NotAuthorizedException (while keeping an eye for any other stuff besides TigaseDBException and UnsupportedOperationException) in the last catch block. Somehow, java eludes my master plan.
Logs show a straight
com.mysql.jdbc.exceptions.MySQLTimeoutException: Statement cancelled due to timeout or client request
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1754)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2019)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1937)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1922)
at tigase.db.jdbc.JDBCRepository.addDataList(JDBCRepository.java:183)
at tigase.db.jdbc.JDBCRepository.setDataList(JDBCRepository.java:1175)
at tigase.db.UserRepositoryMDImpl.setDataList(UserRepositoryMDImpl.java:651)
at tigase.xmpp.RepositoryAccess.setDataList(RepositoryAccess.java:1152)
at tigase.xmpp.RepositoryAccess.setOfflineDataList(RepositoryAccess.java:1204)
**at tigase.xmpp.impl.XGateRoster.setExtraItemsDone(XGateRoster.java:370)**
at tigase.xmpp.impl.DynamicRoster.setExtraItemsDone(DynamicRoster.java:377)
at tigase.xmpp.impl.JabberIqRoster.dynamicSetRequest(JabberIqRoster.java:178)
at tigase.xmpp.impl.JabberIqRoster.process(JabberIqRoster.java:329)
at tigase.server.xmppsession.SessionManager$ProcessorWorkerThread.process(SessionManager.java:2135)
at tigase.util.WorkerThread.run(WorkerThread.java:132)
As far as i can tell, the bolded line in the stack trace should have changed the exception to a NotAuthorizedException breed. What am I missing ?
Thanks
I agree. the problem is not with the code as posted. Check your assumptions. Are there other overloadings of XGateRoster.setExtraItemsDone? Try using Jad to decompile the class file you are running against. If you enable the options to show line numbers, you can be sure the (decompiled) source you are viewing is exactly the code that is executing. Do you know exactly where the log message you are looking at comes from? Maybe it comes from higher up the stack, after it is thrown but before this catch block and exception translation code are even hit.