In C/C++ the filename is returned by FILE and line number is returned by LINE.
Java does have a getFileName(), but does not seem to have a corresponding getLineNumber().
It would be nice to be able to do something like this:
catch (Exception e) {
System.err.println(this.getFileName() + this.getLineNumber() + e.getMessage());
}
Is there a way to get the java file/line number?
public static void main(String[] args)
{
StackTraceElement frame = new Exception().getStackTrace()[0];
System.out.println(frame.getFileName());
System.out.println(frame.getLineNumber());
}
Use this:
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/StackTraceElement.html
Related
I'm trying to rename the file that my program is outputting, but no matter what name i'm trying to change it to, it is stuck with the first name i listed which is "output.txt". I rename it to output1. txt and it still gives me output.txt could someone help with this?
public class Assignment2 {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Sample command: java Assignment2 input.txt");
System.exit(0);
}
try {
Scanner scanner = new Scanner(new File(args[0]));
FileWriter fw = new FileWriter("output1.txt");
int i = 1;
while (scanner.hasNext()) {
System.out.println("Matrix #" + i);
processMatrix(scanner, fw);
i++;
System.out.println("");
fw.write(System.lineSeparator());
}
scanner.close();
fw.close();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
Logger.getLogger(Assignment2.class.getName()).log(Level.SEVERE, null, ex);
}
}
From what I can see there is nothing wrong with your code.
So the only problem I can think of, is you are not building/compiling the file and therefore you are stuck on a older version of that file.
I don't know what technology stack you are using, but a still way to check this since its java, hopefully you got the environment variables configures. Just go to your terminal, to the file folder and:
javac Assignment2.java
java Assignment2
You can also tell me which IDE you are using, or how you are building/running your code.
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)
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");
}
}
I am building an optimization into a JPEG-Encoder written in Java. To do my benchmark i want to extract the orginal code and the optimized code into separated jars. Each jar has to take two arguments. The first on for the file name and the secound for the repeat of the compression of the jpeg.
public static void main(String[] args) {
String filepath = args[0];
try {
int times = Integer.getInteger(args[1]);
runBenchmark(filepath, times);
} catch(IOException | NumberFormatException ioe) {
System.out.println("Your arguments are Wrong! Use the follow order!");
System.out.println("1. Argument must be the filename of the image.");
System.out.println("2. Argument must be a number to repeat the compression.");
}
}
This is my main, witch handle my args. I cant run the arguments on IntellJ . Even if I compile it the a jar, i cant pass my arg2.
I passed two arguments via configuration in intellj and i get a NullPointerException. So i tried to figure out if my java can take two arguments. I wrote a simple main in vim and compiled ran it with two args and worked. I repeated this in a new Project in intellj.
This is working. But why?
You have to check if the parameter is a int or not.
Use Integer.parseInt() and a try-catch block to inform the user if a failure happen.
int times = 0;
try {
times = Integer.parseInt(args[1]);
} catch (Exception e) {
System.out.println("failure with a parameter");
}
I changed the method to Integer.parseInt(string) and now it works. It was the Integer.getInt() it . I thought i had now 2. arg because I get the NullPointerException.
Now it work with this code.
public static void main(String[] args) {
try {
String filepath = args[0];
int times = Integer.parseInt(args[1]);
runBenchmark(filepath, times);
} catch (NumberFormatException nfe) {
System.out.println("2. Arg must be an number");
} catch (IOException ioe) {
System.out.println("File not found.");
} catch(Exception e) {
System.out.println("Your arguments are Wrong! Use the follow order!");
System.out.println("1. Argument must be the filename of the image.");
System.out.println("2. Argument must be a number to repeat the compression.");
}
}
I have these 2 methods to read a number of integers from a file and insert them in a tree. It works fine if the file is found but if the file is not found it doesn't print "File not found". Why is it not going into the catch statement? Thanks!
public static void openF(Tree myT)
{
try
{
x=new Scanner(new File("Number.txt"));
readF(myT);
}
catch(Exception e)
{
System.out.println("File not found");
}
}
// to read from the file
public static void readF(Tree myT)
{
while(x.hasNext()) //keeps going till it reaches the end of file
{
int a =x.nextInt();
myT.insert(a); //insert in tree
}
}
I tested a simplified version of your code:
public static void main(String[] args) {
try {
new Scanner(new File("H:\\Hello.txt"));
System.out.println("The file exists.");
} catch (Exception e) {
System.out.println("File not found: " + e.getMessage());
}
}
When the file exists, it prints The file exists.. If not, it prints File not found: H:\Hello.txt (The system cannot find the file specified).
So no, the catch block is running as expected. The error is somewhere else in your code, but given that you're not providing the full code, nor a part which actually compiles (x is not declared), there is no way for us to guess where the actual error is.