FileInputStream throws NullPointerException - java

I am getting nullpointerexception, don't know what actually is causing it. I read from java docs that fileinputstream only throws securityexception so don't understand why this exception pops up.
here is my code snippet.
private Properties prop = new Properties();
private String settings_file_name = "settings.properties";
private String settings_dir = "\\.autograder\\";
public Properties get_settings() {
String path = this.get_settings_directory();
System.out.println(path + this.settings_dir + this.settings_file_name);
if (this.settings_exist(path)) {
try {
FileInputStream in = new FileInputStream(path + this.settings_dir + this.settings_file_name);
this.prop.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
this.create_settings_file(path);
try{
this.prop.load(new FileInputStream(path + this.settings_dir + this.settings_file_name));
}catch (IOException ex){
//ex.printStackTrace();
}
}
return this.prop;
}
private String get_settings_directory() {
String user_home = System.getProperty("user.home");
if (user_home == null) {
throw new IllegalStateException("user.home==null");
}
return user_home;
}
and here is my stacktrace:
C:\Users\mohamed\.autograder\settings.properties
Exception in thread "main" java.lang.NullPointerException
at autograder.Settings.get_settings(Settings.java:41)
at autograder.Application.start(Application.java:20)
at autograder.Main.main(Main.java:19)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Line 41 is: this.prop.load(in);

If line 41 is this.prop.load(in); then it seems as though this.prop == null
Add a breakpoint on the line to verify.
Attempting to call a method on a null instance results in a NullPointerException.

Is the variable prop null when it is executing on line 41? Try debugging your program to check this. e.g. add
if(prop == null)
System.out.println("prop is null");
Also, NullPointerException is an unchecked exception so isn't documented in Javadoc.

I think the other reviewers did a fair job in explaining your problem.
Couple of pointers:
I noticed that you are catching certain exceptions but not throwing them. If you do not throw the exception then there is no point in catching them.
Secondly, to avoid NPEs you should always check if any of your object is null before executing anything on the object.

Related

Check if an exception was thrown and continue after the exception was thrown

I want to make a test that reads from a file some data and passes that data to a function. That function calls other methods and some of them throw some exceptions. I'm interested in how can I check whether or not calling the method with the parameters from the file triggered an IOException somewhere along. I know that the code snippet provided will stop the execution because I've used assert. How should I write if I want to check if an IOException was thrown and if it was, to get the error message, without stopping the execution of the test? Thanks!
void test() throws IOException {
Service service = helperFunction();
File articles = new File("file.txt");
Scanner scanner = new Scanner(articles);
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
line = line.replaceAll("[^\\d]", " ");
line = line.trim();
line = line.replaceAll(" +", " ");
String[] numberOnTheLine = line.split(" ");
List<Integer> list = Arrays.stream(numberOnTheLine).map(Integer::valueOf).collect(Collectors.toList());
Article article = new Article(Long.valueOf(list.get(0)),
new HashSet<>(List.of(new Version(list.get(1)))));
List<List<Article>> listOfArticles = Collections.singletonList(List.of(article));
Assertions.assertThrows(IOException.class,
() -> service.etlArticles(listOfArticles.stream().flatMap(List::stream).collect(Collectors.toList())));
}
}
Simple; a try/catch statement will take care of it.
Replace this:
service.etlArticles(listOfArticles.stream().flatMap(List::stream).collect(Collectors.toList())));
With:
try {
service.etlArticles(listOfArticles.stream().flatMap(List::stream).collect(Collectors.toList())));
} catch (IOException e) {
// Code jumps to here if an IOException occurs during the execution of anything in the try block
}
You are free to e.g. do some logging and then just Assert.fail, if you want.
assertThrows is quite simple, all it does is this:
try {
runThatCode();
} catch (Throwable e) {
if (e instanceof TypeThatShouldBeThrown) {
// Great, that means the code is working as designed, so, just...
return;
}
// If we get here, an exception was thrown, but it wasn't the right type.
// Let's just throw it, the test framework will register it as a fail.
throw e;
}
// If we get here, the exception was NOT thrown, and that's bad, so..
Assert.fail("Expected exception " + expected + " but didn't see it.");
}
Now that you know how it works, you can write it yourself and thus add or change or log or whatever you want to do during this process at the right place. However given you know it's IOException, instead of an instanceof check you can just catch (IOException e), simpler.

Is this a good way to avoid null return?

I'm currently working on a simple method which converts the content of a file to a string. I saw several topics covering some detail about this question (here). However I can use the try catch or a return do_nothing as mentioned in the previous linked answer. The code:
public static String getStringFromFile(String path) throws EmptyFileException {
String data =null;
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
String line;
while ((line = reader.readLine()) != null) {
data += line +"\n";
}
if (data == null) {
throw new EmptyFileException();
}
}
catch (FileNotFoundException ex) {
showExceptionMessage("File not found");
}
catch (IOException ex) {
showExceptionMessage("Can't read the file");
}
return(data);
}
private static void showExceptionMessage(String message) {
JOptionPane.showMessageDialog(null, message, "ERROR", JOptionPane.ERROR_MESSAGE);
}
So what would be "better" throwing an exception if the file is empty or just using return doNothing() (were doNothing is the function that does nothing, makes sense right? hahah).
Is this a good way to avoid null return?
Yes, always return "existing" object instead of null if you can. Null Object Pattern is a good aproach to avoid that.
So what would be "better" throwing an exception if the file is empty
or just using return doNothing()
In your case throwing an exception is overkill for me. You should throw an exception when you don't expect particular behaviour. Have a look at FileNotFoundException. You always expect that file exists so it's a good choice to throw exception when you can't find this file.
So as metioned above null is bad, so why can't you return empty string? :) In this case it will work like Null Object Pattern, like placeholder :)

Catching Same IOException Inside Catch IOException Block

My Android code is behaving funny. The input stream should and does throw an IOException, which correctly causes control to go to // read an error stream. The error stream is read correctly and the debugger steps to return error_message with the error_message variable containing expected characters read from error stream. It then correctly steps to the // no op in the finally block, which I added just for kicks.
And then, it steps to return "all hope lost";!! Which then, instead of returning to the caller, steps into some Android system code that throws a SecurityException with a message about lack of content permissions.
Removing the finally block has no impact -- the bug still happens. The streams being read are from an HTTP URL Connection. No problems if server returns 200 but if server returns 400 it goes through the weird path described above and tries to throw the weird SecurityException.
try {
// read an input stream into message
return message;
} catch (IOException outer) {
try {
// read an error stream into error_message
return error_message;
} catch (IOException inner) {
return "all hope lost";
}
} finally {
// no op, just to step debugger
}
Update: Posting exact code and debug trace.
try {
/*x*/ BufferedReader buffered_reader =
new BufferedReader(
new InputStreamReader(
new BufferedInputStream(http_url_connection.getInputStream())));
StringBuilder string_builder = new StringBuilder();
String line;
for (line = buffered_reader.readLine();
line != null;
line = buffered_reader.readLine()) {
string_builder.append(line);
}
return string_builder.toString();
} catch (IOException io_exception) {
this.io_exception = io_exception;
BufferedReader buffered_reader =
new BufferedReader(
new InputStreamReader(
new BufferedInputStream(http_url_connection.getErrorStream())));
StringBuilder string_builder = new StringBuilder();
try {
for (String line = buffered_reader.readLine();
line != null;
line = buffered_reader.readLine()) {
string_builder.append(line);
}
/*y*/ String error_message = "server error: " + string_builder.toString();
return error_message;
} catch (IOException exception) {
String level_2_error_message = "level 2 error: " + exception.getMessage();
return level_2_error_message;
} finally {
return "foo";
}
}
Line /*x*/ causes the jump to the first catch as expected. All lines up to /*y*/ are then executed as expected. Then the weird thing is that line /*y*/ does not complete and control immediately goes to either the next catch block if there is no finally or to the finally. If there is a finally then it does not to got the last catch block.
The contents of the string buffer on /*y*/ line look perfectly fine -- a 20 character string from the server.
You say that an exception is being thrown by line /* y */
By my reading of that line of code, the following are plausible explanations:
The exception is a NullPointerException because string_builder is null. But it can't be.
The exception is an OutOfMemoryError because you don't have enough free space for the toString() call to create the new String object.
It is possible that StringBuilder is not java.lang.StringBuilder but some class you wrote yourself. In that case, any exception is possible.
However, I can't see how you would end up in the second IOException handler.
Apart from that, the only other likely explanation is that that source code does not match the code that you are actually executing; e.g. you forgot to recompile something, or you forgot to redeploy after your last compilation.
For what it is worth, your return in your finally is almost certainly a mistake.
It means that you will return "foo" instead of either of the error messages.
If (for example) string_builder.toString() did throw an NPE or OOME, then the return would squash it.
A finally with a return can have non-intuitive behaviour. It is certainly NOT something you should do "for debugging"!!!

Java File Exception Handling

I am supposed to create a sample program for exception handling for file operations for my java assignment. I am having trouble understanding since I am a C++ guy. It would be really very helpful if somebody could point out the flaw in my code below. I am referring this article. Eclipse is giving me "Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body" error.
import java.io.*;
public class file {
public static void main(String[] args) {
String arg1 = args[0];
String arg2 = args[1];
System.out.println(arg1);
System.out.println(arg2);
File f1, f2;
try {
f2 = new File(arg2);
f1 = new File(arg1);
}
catch(FileNotFoundException e) {
/*
if(!f1.exists()) {
System.out.println(arg1 + " does not exist!");
System.exit(0);
}
if(!f2.exists()) {
System.out.println(arg2 + " does not exist!");
System.exit(0);
}
if(f1.isDirectory()) {
System.out.println(arg1 + " is a Directory!");
System.exit(0);
}
if(f2.isDirectory()) {
System.out.println(arg2 + " is a Directory!");
System.exit(0);
}
if(!f1.canRead()) {
System.out.println(arg1 + " is not readable!");
System.exit(0);
}
if(!f2.canRead()) {
System.out.println(arg2 + " is not readable!");
System.exit(0);
}*/
}
}
}
Look at the docs for the File constructor you're calling. The only exception it's declared to throw is NullPointerException. Therefore it can't throw FileNotFoundException, which is why you're getting the error. You can't try to catch a checked exception which the compiler can prove is never thrown within the corresponding try block.
Creating a File object doesn't check for its existence. If you were opening the file (e.g. with new FileInputStream(...) then that could throw FileNotFoundException... but not just creating a File object.
This is because the constructor of class File with one argument
public File(String pathname)
Parameters:pathname - A pathname string Throws: NullPointerException - If the pathname argument is null
Throws: NullPointerException - If the pathname argument is null
throws only one exception and that is NullPointerException. Your code tries to catch a FileNotFoundException which is not related to NullPointerException and this is why you get this error in Eclipse.
One way to go is to catch exceptions of class Exception which is the super class of all exceptions in Java. Another way is to catch all the exceptions (each in different catch block) that the invoked construct throws (which can be easily obtained by going through its API). The third approach is to catch only the exceptions (again which are actually thrown by the construct) that make sense to your application and ignore the others.

Getting error number of an exception object

I have a program developed and it has a single entry point. A Try catch block is surrounding it.
try {
Runner runner = new Runner();
// Adhoc code
UIManager.setLookAndFeel(new NimbusLookAndFeel());
runner.setupVariables();
runner.setLookAndFeel();
runner.startSessionFactory();
runner.setupApplicationVariables();
runner.setupDirectories();
// This will be used to test out frames in development mode
if (Runner.isProduction == true) {
execute();
} else {
test();
}
} catch (Exception e) {
SwingHelper.showErrorMessageMainFrame(e.getMessage());
Logger.getRootLogger().error(e);
e.printStackTrace();
}
But suppose a null pointer exception is thrown, the message box is empty since the Exception doesn't contain a message. For this I added a logic-
if(e instanceof NullPointerException){
NullPointerException n =(NullPointerException) e;
SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at ");
}else{
SwingHelper.showErrorMessageMainFrame(e.getMessage());
}
This works all fine but I also want the line number to be displayed. How can I get it done. How can I get the line number of the exception?
Among the answer to this question, you can use this snippet:
public static int getLineNumber() {
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
Althought is recommended to use a logging library such as log4j.
The metadata for the exception is stored in StackTraceElement class, which you can get from your exception by calling getStackTrace().
Example of using it is:
if (e instanceof NullPointerException) {
NullPointerException n = (NullPointerException) e;
StackTraceElement stackTrace = n.getStackTrace()[0];
SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at " + stactTrace.getLineNumber());
}
if(e instanceof NullPointerException){
NullPointerException n =(NullPointerException) e;
SwingHelper.showErrorMessageMainFrame("Unexpected Exception due at line" + e.getStackTrace()[0].getLineNumber());
} else {
SwingHelper.showErrorMessageMainFrame(e.getMessage());
}
Wow I was ninja'd by those above...
EDIT: Forgot to indent

Categories

Resources