How to get error line number using try/catch in java? - java

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)

Related

Split() fails generating java.lang.ExceptionInInitializerError . How to remove this error?

i am doing splitting on one line of a text file,however i am getting error
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at String[] num= firstline.split(","); line.Can anyone please tell where am i wrong
public class split {
private static java.io.File file;
private static BufferedReader reader;
static int noOfLines=0;
static {
try {
file = new java.io.File("/home/madhu95/Desktop/data.txt");
reader = new BufferedReader(new FileReader(String.valueOf(file)));
while (reader.readLine() != null) {
noOfLines++;
}
System.out.println(noOfLines);
String firstline=reader.readLine();
String[] num= firstline.split(",");
int numberofmobile=Integer.parseInt(num[0]);
System.out.println(numberofmobile);
int numberofDept=Integer.parseInt(num[1]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
while (reader.readLine() != null) {
noOfLines++;
}
This consumes the stream. After this loop is done, you're at the end of the file.
String firstline=reader.readLine();
So this is a lie then - it's not the first line. Not anymore. By counting lines, you are no longer there. In fact, firstline is always going to be null here.
String[] num= firstline.split(",");
. where the thing to the left of it is null, gets you an NPE. You don't catch that, so, your initialization fails. Don't catch that exception - fix the problem where you've forwarded through the entire file by counting lines.
EDIT: Adding a solution that most likely solves all your problems.
Given that you want to know the # of lines before you process them, you'd either need to read the file twice or completely rewrite your logic to no longer need to know # of lines in advance. Complicated, so, instead, what if you don't process the file, but you process a List<String> - which knows how many lines it has (list.size() will get you that information). Then, first read the file into a list of lines, and then take it from there:
import java.nio.file.*;
List<String> lines =
Files.readAllLines(Paths.get("/Path/to/your/data.txt"));
// ....

How to print multiple exceptions in an input file to an errors file?

I'm in a computer science (java) class right now and our task is to create a program that reads integers from an input.txt file (the professor will have this) and prints out all the integers into an output.txt file. Any exceptions/errors will need to be printed to an errors.txt file that our program creates. (We are learning about Exceptions in class now).
My program is able to read from an input file and print out just the integers to an output.txt, but I'm having problems printing out all the exceptions that might occur. For example, if the input file has "abc" as one of the lines, it should print out a message in the errors.txt file saying that it isn't an integer.
What happens with my program is that as soon as one exception is thrown, it doesn't keep going to print out all the other exceptions even if there are more to print. It just stops at that point.
So for example, something like this:
try{
while (fileScan.hasNext())
{
num = fileScan.nextInt();
}
}catch(Exception e)
{
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
erout is my PrintWriter object for the error.txt file. fileScan for the input.txt.
I'm just not sure how to get it to go through all of the input.txt file and keep track of all the exceptions it will throw, then print all those to an error.txt file. Any help would be appreciated, thanks. :)
You could move the while loop outside of the try statement.
while (fileScan.hasNext())
{
try{
num = fileScan.nextInt();
}catch(Exception e)
{
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
}
You need to re-order your while and try/catch:
List<Exception> exceptions = new ArrayList<>();
while (fileScan.hasNext()) {
try {
num = fileScan.nextInt();
// more code here to process num
} catch (Exception e) {
// Might also want to create a custom exception type to track
// The line/file that the error occurred upon.
exceptions.add(e);
fileScan.nextLine();
}
}
All you gotta do is move the try/catch within the while:
while (fileScan.hasNext())
{
try {
num = fileScan.nextInt();
}
catch (Exception e) {
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
}

Run Jar file with more than one argument

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.");
}
}

EOFException - how to handle?

I'm a beginner java programmer following the java tutorials.
I am using a simple Java Program from the Java tutorials's Data Streams Page, and at runtime, it keeps on showing EOFException. I was wondering if this was normal, as the reader has to come to the end of the file eventually.
import java.io.*;
public class DataStreams {
static final String dataFile = "F://Java//DataStreams//invoicedata.txt";
static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
static final int[] units = { 12, 8, 13, 29, 50 };
static final String[] descs = {
"Java T-shirt",
"Java Mug",
"Duke Juggling Dolls",
"Java Pin",
"Java Key Chain"
};
public static void main(String args[]) {
try {
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));
for (int i = 0; i < prices.length; i ++) {
out.writeDouble(prices[i]);
out.writeInt(units[i]);
out.writeUTF(descs[i]);
}
out.close();
} catch(IOException e){
e.printStackTrace(); // used to be System.err.println();
}
double price;
int unit;
String desc;
double total = 0.0;
try {
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
while (true) {
price = in.readDouble();
unit = in.readInt();
desc = in.readUTF();
System.out.format("You ordered %d" + " units of %s at $%.2f%n",
unit, desc, price);
total += unit * price;
}
} catch(IOException e) {
e.printStackTrace();
}
System.out.format("Your total is %f.%n" , total);
}
}
It compiles fine, but the output is:
You ordered 12 units of Java T-shirt at $19.99
You ordered 8 units of Java Mug at $9.99
You ordered 13 units of Duke Juggling Dolls at $15.99
You ordered 29 units of Java Pin at $3.99
You ordered 50 units of Java Key Chain at $4.99
java.io.EOFException
at java.io.DataInputStream.readFully(Unknown Source)
at java.io.DataInputStream.readLong(Unknown Source)
at java.io.DataInputStream.readDouble(Unknown Source)
at DataStreams.main(DataStreams.java:39)
Your total is 892.880000.
From the Java tutorials's Data Streams Page, it says:
Notice that DataStreams detects an end-of-file condition by catching EOFException, instead of testing for an invalid return value. All implementations of DataInput methods use EOFException instead of return values.
So, does this mean that catching EOFException is normal, so just catching it and not handling it is fine, meaning that the end of file is reached?
If it means I should handle it, please advise me on how to do it.
EDIT
From the suggestions, I've fixed it by using in.available() > 0 for the while loop condition.
Or, I could do nothing to handle the exception, because it's fine.
While reading from the file, your are not terminating your loop. So its read all the values and correctly throws EOFException on the next iteration of the read at line below:
price = in.readDouble();
If you read the documentation, it says:
Throws:
EOFException - if this input stream reaches the end before reading eight bytes.
IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
Put a proper termination condition in your while loop to resolve the issue e.g. below:
while(in.available() > 0) <--- if there are still bytes to read
The best way to handle this would be to terminate your infinite loop with a proper condition.
But since you asked for the exception handling:
Try to use two catches. Your EOFException is expected, so there seems to be no problem when it occures. Any other exception should be handled.
...
} catch (EOFException e) {
// ... this is fine
} catch(IOException e) {
// handle exception which is not expected
e.printStackTrace();
}
You can use while(in.available() != 0) instead of while(true).
Alternatively, you could write out the number of elements first (as a header) using:
out.writeInt(prices.length);
When you read the file, you first read the header (element count):
int elementCount = in.readInt();
for (int i = 0; i < elementCount; i++) {
// read elements
}
You may come across code that reads from an InputStream and uses the snippet
while(in.available()>0) to check for the end of the stream, rather than checking for an
EOFException (end of the file).
The problem with this technique, and the Javadoc does echo this, is that it only tells you the number of blocks that can be read without blocking the next caller. In other words, it can return 0 even if there are more bytes to be read. Therefore, the InputStream available() method should never be used to check for the end of the stream.
You must use while (true) and
catch(EOFException e) {
//This isn't problem
} catch (Other e) {
//This is problem
}
You catch IOException which also catches EOFException, because it is inherited. If you look at the example from the tutorial they underlined that you should catch EOFException - and this is what they do. To solve you problem catch EOFException before IOException:
try
{
//...
}
catch(EOFException e) {
//eof - no error in this case
}
catch(IOException e) {
//something went wrong
e.printStackTrace();
}
Beside that I don't like data flow control using exceptions - it is not the intended use of exceptions and thus (in my opinion) really bad style.
Put your code inside the try catch block:
i.e :
try{
if(in.available()!=0){
// ------
}
}catch(EOFException eof){
//
}catch(Exception e){
//
}
}
EOFException being a child of IOException
I prefer it like below ==>
try {
.
.
.
} catch (IOException e) {
if (!(e instanceof EOFException)) {
throw new RuntimeException(e);
}
}

Is there a way to get the java file/line number?

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

Categories