without try catch

Hi,

When i ran below program without try catch

package com.mkyong.file;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class BufferedReaderExample {
 
	public static void main(String[] args) {
 
		BufferedReader br = null;
 
	//	try {
 
			String sCurrentLine;
 
			br = new BufferedReader(new FileReader("C:/Users/Desktop/gpfolder/gpmy/personal/newfile.txt"));
 
			while ((sCurrentLine = br.readLine()) != null) {
				System.out.println(sCurrentLine);
			}
 
		//} catch (IOException e) {
	//		e.printStackTrace();
//		} finally {
//			try {
//				if (br != null)br.close();
//			} catch (IOException ex) {
//				ex.printStackTrace();
//			}
//		}
 
	}
}
//}

Open in new window


I see clear stack trace generated as below with line numbers

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
      Unhandled exception type FileNotFoundException
      Unhandled exception type IOException

      at com.mkyong.file.BufferedReaderExample.main(BufferedReaderExample.java:17)


SO in this case why we need complicated try catches when stack trace is doing its work. Who prints stack trace compiler or jvm or program.

alos in IO programs why  always have to reverse forward slash to reverse slash of windlows path to make it work.

java program path
C:/Users/Desktop/gpfolder/gpmy/personal/newfile.txt
windows path in laptop
C:\Users\Desktop\gpfolder\gpmy\personal\newfile.txt


Please advise.


Any links resources ideas highly appreciated. Thanks in advance
LVL 7
gudii9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Michel PlungjanIT ExpertCommented:
The idea is of course that you handle the exception and show a relevant error message to the end user instead of Unhandled exception type FileNotFoundException

Sometimes a catch does not need to do anything since it maybe normal that the file is not found when you try to delete it the first time or create a directory that already exists
0
rrzCommented:
> in IO programs why  always have to reverse forward slash to reverse slash of windlows path to make it work.
The backslash character (\) is an escape character.  See "Escape Sequences" at
http://docs.oracle.com/javase/tutorial/java/data/characters.html
But, on Windows operating systems, the backslash character is also a delimiting character for file paths. See
http://en.wikipedia.org/wiki/Path_(computing) 
In your code, you can always use  File.separator. See
http://docs.oracle.com/javase/7/docs/api/java/io/File.html#separatorChar
http://stackoverflow.com/questions/2417485/file-separator-vs-slash-in-paths
Or you can use the escape sequence. For example
New FileReader(C:\\Users\\Desktop\\gpfolder\\gpmy\\personal\\newfile.txt)
But, if you want to make life easy for yourself, just use /
new FileReader("C:/Users/Desktop/gpfolder/gpmy/personal/newfile.txt")
And forget about Windows  little quirk.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Michel PlungjanIT ExpertCommented:
That was not the actual question I think
0
Introduction to R

R is considered the predominant language for data scientist and statisticians. Learn how to use R for your own data science projects.

rrzCommented:
He asked two questions.
0
rrzCommented:
>New FileReader(C:\\Users\\Desktop\\gpfolder\\gpmy\\personal\\newfile.txt)  
Error! That should have been,
new FileReader("C:\\Users\\Desktop\\gpfolder\\gpmy\\personal\\newfile.txt")
0
dpearsonCommented:
SO in this case why we need complicated try catches when stack trace is doing its work. Who prints stack trace compiler or jvm or program.

For a very simple program that just exits when there's an error, then you don't need to write your own try {} catch { printStackTrace() ; } logic.

However, in more complex programs typically the whole program does not exit when there's a single error.  In those situations you will want to know how to print a stacktrace to show where the error happened and then keep on executing.

As for who prints the stack trace - that's the java runtime that is printing it.  If a Java program executed at the command line terminates with an exception, the runtime prints out that exception.

Hope that helps,

Doug
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
SO in this case why we need complicated try catches when stack trace is doing its work
Just checking, you do realise that this is NOT the same stack trace that would ever be printed out by the ex.printStackTrace(); on line 29 (had it not been commented out).

The stack trace that you got is from Java saying, "I can't run your program because I am unable to compile it due to a problem on line 17. That line calls a method that can throw IOExceptions and/or FileNotFoundExceptions and you MUST catch these exceptions". Note this... your program hasn't actually executed.

This is very different from what you get if you uncomment those lines. In that case, your program WILL be executed and then "if" the method call on line 17 encounters a problem, it will throw either IOException or FileNotFoundException that is caught by your catch statement and then line 29 prints the stack trace. As hinted by others, it is done in this way because there is any number of ways that these problems should be dealt with depending on what you are coding.


If you DO want your program to execute and you DON'T want to have to handle these potential problems yourself, this is the way that you would handle it...
package com.mkyong.file;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class BufferedReaderExample {

    public static void main(String[] args) throws IOException {

        BufferedReader br = null;

        try {
            String sCurrentLine;

            br = new BufferedReader(new FileReader("C:/Users/Desktop/gpfolder/gpmy/personal/newfile.txt"));

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

        } finally {
            if (br != null)br.close();
        }
    }
}

Open in new window

The important part to note is line 9, notice the throws IOException that I have added to the definition of your "main" method? What you are now saying is that some code in this method *may* throw an IOException and since we aren't handling here (with a catch statement), this exception should subsequently propagate to the caller of this "main" method. Since it is the JVM that is the caller of your main method, then it is the JVM that will catch the exception and print out a stack trace for you. (Note, I have left in the "finally" clause because it is still a good idea to manage your resources properly, even if you do allow the exception to propagate up. Although in this simple program you probably wouldn't worry about)
0
gudii9Author Commented:
>>>>New FileReader(C:\\Users\\Desktop\\gpfolder\\gpmy\\personal\\newfile.txt)  
>>Error! That should have been,
>>new FileReader("C:\\Users\\Desktop\\gpfolder\\gpmy\\personal\\newfile.txt")

difference is 'n' should be small letter not capital in the 'new'

please advise
0
rrzCommented:
>difference is 'n' should be small letter not capital in the 'new'.
Yes, and double quotes need to be around file path string.
0
gudii9Author Commented:
>> notice the throws IOException that I have added to the definition of your "main" >>method

now i got below exception from caller(here jvm)


Exception in thread "main" java.io.FileNotFoundException: C:\Users\Desktop\gpfolder\gpmy\personal\newfile.txt (The system cannot find the path specified)
      at java.io.FileInputStream.open(Native Method)
      at java.io.FileInputStream.<init>(FileInputStream.java:120)
      at java.io.FileInputStream.<init>(FileInputStream.java:79)
      at java.io.FileReader.<init>(FileReader.java:41)
      at com.jpmc.ccs.cafad.dif.ala.job.BufferedReaderExample.main(BufferedReaderExample.java:16)



SO in this case why we need complicated try catches when stack trace is doing its work
Just checking, you do realise that this is NOT the same stack trace that would ever be printed out by the ex.printStackTrace(); on line 29 (had it not been commented out).


I am not cler on above sentence. can you please elaborate.
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
now i got below exception from caller(here jvm)
Which shows what I was talking about... that you DON'T have to have a catch block with an "ex.printStackTrace()" call to get the stack trace printed. In this case the FileNotFoundException has been propagated back to the caller of your "main" method, ie. the JVM, which has then caught that exception and printed the stack trace.

I am not making any assertions here as to what is "best practise" for handling errors, because in 90% of cases this probably ISN'T, but it is merely to demonstrate what is happening.


I am not cler on above sentence. can you please elaborate
What I was saying was that the original stack trace that you posted in your question, the one showing java.lang.Error: Unresolved compilation problems, is totally different to Exceptions that the code that YOU write might throw, such as the FileNotFoundException that you have just posted. The first exception was indicating compilation errors that you have ignored and said to proceed with launching the code. Yes, it is an exception that happens at run-time but it is indicating a compile-time problem (it is something particular to Eclipse that it still lets you run code that can't be fully compiled). It is totally different to run-time issues, such as a file not being able to be found at that particular time that you run the code. It is these run-time issues that try catch is really there to cater for.
0
gudii9Author Commented:
The first exception was indicating compilation errors that you have ignored and said to proceed with launching the code. Yes, it is an exception that happens at run-time but it is indicating a compile-time problem (it is something particular to Eclipse that it still lets you run code that can't be fully compiled).
Actually when i try to run this time on other machine as below

package com.xyz;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {

	public static void main(String[] args) {

		BufferedReader br = null;

	//	try {

			String sCurrentLine;

			br = new BufferedReader(new FileReader("C:/Users/Desktop/gpfolder/gpmy/personal/newfile.txt"));

			while ((sCurrentLine = br.readLine()) != null) {
				System.out.println(sCurrentLine);
			}

		//} catch (IOException e) {
	//		e.printStackTrace();
//		} finally {
//			try {
//				if (br != null)br.close();
//			} catch (IOException ex) {
//				ex.printStackTrace();
//			}
//		}

	}
}
//}

Open in new window


I see this eclipse version showing errors

line 17 says -->resource leake, br never closed also unhandled filenotfound exception

then line 19 says-->unhandled IO exception
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.