This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have made a main class as well to run it, but it is throwing out an NPE NullPointerException at the readFile() method. I'm not sure why this is occurring.
/* this code is to read from a file testfile.txt which is already made beforehand with data in it*/
import java.io.*; //imported files
import java.util.*;
public class file_read {
private Scanner x; //for reading from file
public void openFile() {
try {
x = new Scanner(new File("testfile.txt"));
} catch (Exception e) {
System.out.println("error occurred");
}
}
public void readFile() { //error in this method(NPE)
while (x.hasNext()) {
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s \n", a, b, c);
}
}
public void closeFile() {
x.close();
}
}
public class file_read_main {
public static void main(String[] args) {
file_read obj = new file_read();
obj.openFile();
obj.readFile();
obj.closeFile();
}
}
This is one class. The other class is already made having main() in it having object of this class as well as calling of the methods from the object.
The problem is that x is null.
Based on the code that you have shown, this can only be because an exception is being thrown in openFile(), and you are ignoring it.
Make openFile throw its exception:
public void openFile() throws IOException {
x = new Scanner(new File("testfile.txt"));
}
(you will need to add throws IOException to your main method too)
Now the fact that an IOException has been thrown will stop your code executing, so it won't try to read the file.
Assuming you've got no default exception handler set up, you will also get the stack trace of the exception, which will include details of why the exception was thrown.
As a general principle about exception handling, don't catch Exception, unless that's really the exception that you really need to handle. It catches all exceptions, and might accidentally catch certain exception types which really should be handled separately.
You should also not just swallow exceptions unless you are really sure that is the right thing to do. The bare minimum you should do with an exception is to print its stack trace in the catch:
e.printStackTrace();
This is not the best choice in the current situtation, however, since you actually need to stop further execution in the calling method: propagating the exception is a better choice.
Related
I have the class Parser in Java like below:
public class Parser {
public ArrayList<MetroStop> listeArrets;
public Parser() {
this.listeArrets = new ArrayList<>();
}
public MetroStop creerArret(String [] parts) {
MetroStop arret = new MetroStop ();
arret.identifiant = Integer.parseInt(parts [0]);
arret.longitude = Double.parseDouble(parts [1]);
arret.latitude = Double.parseDouble(parts [2]);
arret.nom = parts [3];
arret.destination = parts [4];
arret.moyen = parts [5];
return arret;
}
public void parse(String fichier) throws Exception {
try {
Reader reader = new FileReader(fichier);
BufferedReader br = new BufferedReader(reader);
String line;
while((line = br.readLine ()) != null) {
String [] parts = line.split("#");
MetroStop arret = creerArret(parts);
listeArrets.add(arret);
}
br.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
}
I also have the Main class:
public class Main {
public static void main(String[] argv) {
Parser teste = new Parser();
teste.parse("ratp_arret.csv");
}
}
When I run the Main class as Java Application i get this error:
"Unhandled exception type Exception", which points to the second line of the main() method.
The file ratp_arret.csv is located in the src folder, which is also the working directory.I am using Eclipse.
I don't understand where this error comes from.
Thank you for your help!
You call teste.parse(someString), where teste is an expression which has type Parser. That means this is a call to the method parse(String) in your Parser type....
and that is declared with throws Exception.
Exceptions are a mechanism to convey alternate return options. The parse method can run its course in one of two ways: It can 'return', in which case it returns nothing (void), or, it can 'throw'. What it can throw is limited by its throws line - in this case, it can throw just about anything (Exception is the supertype of almost all things you can throw).
The way java handles this is that your code needs to handle every possible way a method can conclude.
So, you need a 'path' for your code when the parser() method returns (this is trivial; it's a void method, you get that 'for free', you don't need to write anything special for this), but you also need a path for that other exit scenario: When it throws something. You get handling of RuntimeException for free, but for others, you have two options:
catch it:
try {
teste.parse(someString);
// this code runs in the 'return' case.
} catch (Exception e) {
// this code runs in the 'throws' case.
}
this would imply you know what to do when your parse method decided to exit via the throws path.
Alternatively, you fix this by having your main method also 'fork', and decree that it has two ways to finish: Either via the return route or the throw route:
public static void main(String[] args) throws Exception {
teste.parse(someString);
}
// this main method has declared that it has two separate
// exit routes. 'return', and 'throws something'.
java will start an application by running its main method, and java can deal with a main that has two alternate exit routes (return, or throw something). It handles the 'return' route by doing nothing. It handles the 'throw something' route by printing the type of the exception, the message, the stack trace, and the entire causal chain. That is an excellent default, and you should not attempt to come up with a different one by e.g. catching that exception and attempting to 'log it'.
This: Just add throws Exception to your main method declaration. Put the throws Exception back on your parse method, ignore #Eritrean's advice.
NB: All methods are inherently declared as if they said throws RuntimeException, Error (as in, any error and any runtimeexception can be thrown without writing a throws clause for it, as all methods implicitly have that clause baked in already), this is why I said earlier that RuntimeExceptions are 'handled for free'. The idea is that all exceptions that subclass RuntimeException are things that are so universal or so unlikely, it would be unwieldy to force management of this onto the programmer. That's why you never need to write throws NullPointerException or throws InternalError.
public void parse(String fichier) /*throws Exception*/ {
try {
// ...
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
You throw RuntimeException. This is called not-checked exception and it's not mandatory to declare these exeptions in the method declaration and catch it when calle the method.
My question is when we use "throws" methodology to throw an exception, why we need to give it in front of main method inspite of already thrown it in respective method which required that like add() method will throw the exception if am using Inputstream reader to take the input, so i used "throws IOException" in front of it and executed the code. But error was coming to handle the IOexception in main thread. So, when i appended "throws IOException" in front of main thread, it executed fine. But i did not get why error was coming in main thread part as add() method was the one to generate the exception and there i handled it.
Please explain this. :)
Code:
class A {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
public void add() throws IOException {
int a=Integer.parseInt(br.readLine());
int b=Integer.parseInt(br.readLine());
System.out.println("Value after addition : "+(a+b));
}
public static void main(String args[]) throws IOException {
A a=new A(); a.add();
}
}
But i did not get why error was coming in main thread part as add() method was the one to generate the exception and there i handled it.
No, you didn't handle it there. You let it propagate up to the calling method.
Handling an exception means catching it and doing something appropriate:
public static void main(String args[]) {
A a=new A();
try {
a.add();
} catch (IOException e) {
// Don't really know how you want to handle it, so I'll just print a line on System.err.
System.err.println("add() failed!");
}
}
When you use "throws" you don't treat your exception. you just say that you don't want to treat it there and you will treat it in other place (the place you call the method).So throwing it from the method means that you have to treat it from the main or any other place you call your method
Is there a way to handle an exception in the constructor.
Everytime I use the getter into another method I have to declare the exception again. I tried a try/catch block inside the constructor but still asking for other method to declare the exception.
public Question() {
try {
this.file = new File("questions.txt");
} catch (Exception e) {
System.out.println("Could not find file");
System.out.println("Check file path is correct");
}
counterIndex = 0;
questionSetup();
}
public Question() throws FileNotFoundException {
file = new File("questions.txt");
counterIndex = 0;
questionSetup();
}
public ArrayList<String> getQuestionArr() {
return questionArr;
}
public File getFile() {
return file;
}
Throw it from the constructor, and handle it anywhere else. When a constructor encounters an exceptional situation, it should throw an exception instead of continuing along and fully constructing an object.
Imagine if FileInputStream didn't throw a FileNotFoundException.
FileInputStream fis = new FileInputStream("~/iDontReallyExist.bin");
// appears to work
// then later, long after you've instantiated `fis`
fis.read(buffer); // <-- boom?
Constructors can and should throw exceptions whenever something breaks. Code calling the constructor (or higher up in the stack) handle it as they see fit (trying again, failing, etc.). As a bonus, the half constructed object becomes available for garbage collection without you needing to be too concerned about it.
Assuming that Question() throws a FileNotFoundException, you can handle an error something like this (I don't know your real app obviously, so this is made up as an example of error handling):
Question loadQuestion(int id) throws FileNotFoundException {
return new Question(getQuestionPath(id));
}
called by:
Set<Question> getQuestionsByCategory(QuestionCategory category) {
Set<Integer> ids = getQuestionIds(category);
Set<Question> questions = new HashSet<Question>();
for (Integer id : ids) {
try {
questions.add(loadQuestion(id));
} catch (FileNotFoundException ex) {
somelogger("File not found loading question ID " + id, ex);
throw ex;
}
}
return questions;
}
and finally
public static void main(String[] args) throws FileNotFoundException {
Set<Questions> questions = QuestionsLoader
.getQuestionsByCategory(QuestionCategory.valueOf(args[0]));
}
In this example, I log it in code responsible for loading questions by category, then re-throw it to let it blow up. I chose to do that because not being able to open a local file seems like something fatal here, but you're not constrained to do that. You could instead simply not include the question in the returned results, or ask for a different path to search. The bottom line of what to do upon an error is ultimately in context of what you need.
Okay for a class I had to build a queue ADT and use that ADT to create an application that does basic adding/subtracting. The problem is that when I try to invoke the queue's methods that have an exception linked to them I get " error: unreported exception FullCollectionException; must be caught or declared to be thrown".
Here is what my code looks like.
public void insert(Object element) throws FullCollectionException
{
if(isFull())
throw new FullCollectionException("Queue");
else
{
queue[count] = element;
count++;
}
}
The isFull method just does a simple comparison to see if the array has met its length. Then the class that uses it is as follows.
public class Stocks
{
public static void main(String a[])
{
Queue q = new Queue();
StackObject so = new StackObject();
q.insert(10);
q.insert(30);
}
}
I tried several different things but none seemed to work.
Unless FullCollectionException is a child of RuntimeException (which is unchecked), you won't be able to do that. Try this:
try {
q.insert(10);
q.insert(30);
} catch (FullCollectionException fce) {
// Handle exception
}
You need to declare that main() could potentially throw that exception, like this:
public static void main(String a[]) throws FullCollectionException
{
Queue q = new Queue();
StackObject so = new StackObject();
q.insert(10);
q.insert(30);
}
Or you could add a catch block instead, but you should only ever do that if you have an actual plan to recover from the exception. Otherwise, it's actually better to let your program fail rather than silently sweep problems under the rug.
You need to explicitly throw or catch the FullCollectionException in the main method.
PS: if you use an IDE such as Eclipse or Netbeans to write your code, you will be prompted to add such exception handling statements.
Figured it out. I made the exceptions as part of my assignment and I just had them be a child of Exception instead of RuntimeException. Thanks for all your help :))
Can someone please explain to me the throws Exception part in the following code?
public static void main(String args[]) throws Exception {
//do something exciting...
}
Thank you in advance.
it means the function main(String[]) can throw any sub-type of Exception. in Java, all exceptions thrown by a method(except RunTimeException) must be explicitly declared.
that means every method using main(String[]) will have to take care (try,catch) Exception, or declare itself as throwing Exception as well.
Exceptions are a way Java uses to act when something unexpected happened. For example, if you want to read/write from/to a file, you have to handle IOException that will be thrown if there is a problem with the file.
A little example to explain that to you:
Let's take a method called method1() that throws an exception:
public void method1() throws MyException {
if (/* whatever you want */)
throw new MyException();
}
It can be used in two ways. The first way with method2() will simply toss the hot potatoe further:
public void method2() throws MyException {
method1();
}
The second way with method3() will take care of that exception.
public void method3() {
try {
method1();
}
catch (MyException exception) {
{
/* Whatever you want. */
}
}
For more information about exceptions, http://download.oracle.com/javase/tutorial/essential/exceptions/ should help.
EDIT
Let's say we want to return the containt of a value in this array (which is the square of the entered number): int[] squares = {0, 1, 4, 9, 16, 25}; or 0 if the number (input) is too big.
Pedestrian Programming:
if (input > squares.length)
return 0;
else
return squares[input];
Exception Guru Programming:
try {
return squares[input];
}
catch (ArrayIndexOutOfBoundException e) {
return 0;
}
The second example is cleaner, for you can also add another block (and another again) after that, so that every possible problem is fixed. For example, you can add this at the end:
catch (Exception e) { // Any other exception.
System.err.println("Unknown error");
}