Exception handling code doubt - java

I am very new to this topic. Please bare with my silly doubts. I have the following code where I get a name from user and if its null sone exception is thrown. But here i m not getting any exception it i enter null. Please help me
import java.io.*;
class dbz
{
public static void main(String args[])
{
String s=null;
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
s=br.readLine();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
System.out.println(s);
}
}

You will never receive null as user input from the console, and it would not trigger a IOException regardless.

modify your code as below then you'll see the problem for yourself
import java.io.*;
class dbz
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(br.readLine());
}
}

Related

Java BufferedReader.readLine() not waiting for user input

I am having an issue with my instance of BufferedReader not waiting for the user to input before moving forward.
static BufferedReader in;
public class {
public static void main(String[] args) {
try{
in = new BufferedReader(new InputStreamReader(System.in));
String input;
System.out.println("prompt");
input = in.readLine();
if(input.equals("Y")){
//do something
}else {
//do something else
}
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
What happens is I when I run the program, it simply skips over the in.readLine() and throws a null exception at the if statement. I am at a loss on what is happening, as I used the same code for another project that still works.
Thanks!
Found the answer. Using gradle to run the program and my task didn't have the parameter for standardInput = System.in. Still getting used to project building software!
Yes you have to treat the exception, just add this:
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
String input;
System.out.println("prompt");
input = in.readLine();
if(input.equals("Y")){
System.out.println("it works !!");
}else {
System.out.println("it's not a Y :(");
}
}

Buffered reader causing an infinite loop

I'm currently doing a test project to understand how to read/write into a text file. This is my code:
package testings;
import java.util.Scanner;
import java.io.*;
public class Writing_Reading_files {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
File testFile = new File("testFile.dat");
String test, sName;
try{
PrintWriter print = new PrintWriter(new BufferedWriter(new FileWriter(testFile)));
test = in.nextLine();
print.println(test);
print.close();
}catch(IOException e) {
System.out.println("IO exception");
System.exit(0);
}
try {
BufferedReader readerName = new BufferedReader(new FileReader(testFile));
while(readerName != null) {
sName = readerName.readLine();
System.out.println(sName);
}
readerName.close();
} catch(FileNotFoundException e) {
System.out.println("FileNotFound");
System.exit(0);
} catch(IOException e) {
System.out.println("IO exception");
System.exit(0);
}
}
}
The while loop results in spitting out the line I put then nulls for an infinite loop if I try While(readerName.readLine != null) it stops the infinite loop but only outputs a null and I don't know where to go from there, I've tried following a youtube tutorial but he has it the same as my code so I'm unsure why I'm null keeps repeating. Thanks in advance for any help.
why would readerName become null? Maybe you mean that the String returned by readLine is null?
Consider
BufferedReader readerName = new BufferedReader(new FileReader(testFile));
String sName = readerName.readLine();
while(sName != null) {
System.out.println(sName);
sName = readerName.readLine();
}
Also consider using try-with-resources when opening your file.

Bad practice in JDK's try-with-resources example? [duplicate]

This question already has answers here:
Correct idiom for managing multiple chained resources in try-with-resources block?
(8 answers)
Closed 5 years ago.
I found this example in the try-with-resources documentation for Java:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
If the constructor for BufferedReader throws an exception, then the resources held by the FileReader won't be released. So isn't this a bad practice to write it like that instead of:
static String readFirstLineFromFile(String path) throws IOException {
try (FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr)) {
return br.readLine();
}
}
Indeed, just gave it a quick try:
public class MyFileReader extends FileReader {
public MyFileReader(String fileName) throws FileNotFoundException {
super(fileName);
}
#Override
public void close() throws IOException {
System.out.println("Closing MyFileReader");
super.close();
}
}
public class MyBufferedReader extends BufferedReader {
public MyBufferedReader(Reader in) {
super(in);
throw new RuntimeException();
}
#Override
public void close() throws IOException {
System.out.println("Closing MyBufferedReader");
super.close();
}
}
public String test(String path) throws IOException {
try (BufferedReader br = new MyBufferedReader(new MyFileReader(path))) {
return br.readLine();
}
}
None of MyFileReader nor MyBufferedReader is closed... Good catch!
While with:
public String test(String path) throws IOException {
try (FileReader fr = new MyFileReader(path); BufferedReader br = new MyBufferedReader(fr)) {
return br.readLine();
}
}
MyFileReader is closed.
BufferedReader constructor can indeed throw exceptions, see BufferedReader(Reader in, int sz) constructor (although not when coming from BufferedReader(Reader in) constructor, but the doc you linked should still alert on this possible issue IMHO).
Looks like you won the right to raise an issue :)
Unfortunately, you are right.
The below example shows this behaviour - instance of Internal is never closed.
public class Test {
public static void main(String[] args) {
try (External external = new External(new Internal())) {
}
}
}
class External implements Closeable {
private Internal internal;
public External(Internal internal) {
this.internal = internal;
throw new RuntimeException("boom");
}
#Override
public void close() {
System.out.println("External.close()");
internal.close();
}
}
class Internal implements Closeable {
#Override
public void close() {
System.out.println("Internal.close()");
}
}

Unreported exception java.io.FileNotFoundException;?

I want to open a file and scan it to print its tokens but I get the error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
Scanner stdin = new Scanner (file1); The file is in the same folder with the proper name.
import java.util.Scanner;
import java.io.File;
public class myzips {
public static void main(String[] args) {
File file1 = new File ("zips.txt");
Scanner stdin = new Scanner (file1);
String str = stdin.next();
System.out.println(str);
}
}
The constructor for Scanner you are using throws a FileNotFoundException which you must catch at compile time.
public static void main(String[] args) {
File file1 = new File ("zips.txt");
try (Scanner stdin = new Scanner (file1);){
String str = stdin.next();
System.out.println(str);
} catch (FileNotFoundException e) {
/* handle */
}
}
The above notation, where you declare and instantiate the Scanner inside the try within parentheses is only valid notation in Java 7. What this does is wrap your Scanner object with a close() call when you leave the try-catch block. You can read more about it here.
The file is but it may not be. You either need to declare that your method may throw a FileNotFoundException, like this:
public static void main(String[] args) throws FileNotFoundException { ... }
or you need to add a try -- catch block, like this:
Scanner scanner = null;
try {
scanner = new Scanner(file1);
catch (FileNotFoundException e) {
// handle it here
} finally {
if (scanner != null) scanner.close();
}

Java Try and Catch IOException must be caught or declared to be thrown

I am trying to use a bit of code I found at the bottom of this page. Here is the code in a class that I created for it:
import java.io.LineNumberReader;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
public static int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
int cnt = 0;
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {}
cnt = reader.getLineNumber();
reader.close();
return cnt;
}
}
My objective is to count the lines of a text file, store that number as an integer, then use that integer in my main class. In my main class I tried a few different ways of making this happen, but (being a new programmer) I am missing something. Here is the first thing I tried:
String sFileName = "MyTextFile.txt";
private int lineCount = LineCounter.countLines(sFileName);
With this attempt I get the error "unreported exception java.io.IOException; must be caught or declared to be thrown." I don't understand why I am getting this because as I can see the exception is declared in my "countLines" method. I tried to use a try catch block right under that last bit of code I posted, but that didn't work either (I don't think I did it right though). Here is my try catch attempt:
String sFileName = "MyTextFile.txt";
private int lineCount;{
try{
LineCounter.countLines(sFileName);
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
}
Please show me the way!
Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.
private int lineCount; {
try{
lineCount = LineCounter.countLines(sFileName);
/*^^^^^^^*/
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
}
Also, your countLines can be made simpler:
public static int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
while (reader.readLine() != null) {}
reader.close();
return reader.getLineNumber();
}
Based on my test, it looks like you can getLineNumber() after close().
The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:
public static void main(String[] args) {
int lines = 0;
// TODO - Need to get the filename to populate sFileName. Could
// come from the command line arguments.
try {
lines = LineCounter.countLines(sFileName);
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
if(lines > 0) {
// Do rest of program.
}
}
Your countLines(String filename) method throws IOException.
You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.
Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.
Try this to just throw the IOException from main
public class MyClass {
private int lineCount;
public static void main(String[] args) throws IOException {
lineCount = LineCounter.countLines(sFileName);
}
}
or this to handle it and wrap it in an unchecked IllegalArgumentException:
public class MyClass {
private int lineCount;
private String sFileName = "myfile";
public static void main(String[] args) throws IOException {
try {
lineCount = LineCounter.countLines(sFileName);
} catch (IOException e) {
throw new IllegalArgumentException("Unable to load " + sFileName, e);
}
}
}

Categories

Resources