Unhandled exception type Exception in Eclipse - java

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.

Related

what is the major difference between the given 2 programs having TRY & CATCH and THROWS exception in JAVA [duplicate]

So I thought I had a good basic understanding of exception-handling in Java, but I was recently reading some code that gave me some confusion and doubts. My main doubt that I want to address here is when should a person use throws in a Java method declaration like the following:
public void method() throws SomeException
{
// method body here
}
From reading some similar posts I gather that throws is used as a sort of declaration that SomeException could be thrown during the execution of the method.
My confusion comes from some code that looked like this:
public void method() throws IOException
{
try
{
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
Is there any reason that you would want to use a throws in this example? It seems that if you are just doing basic exception-handling of something like an IOException that you would simply need the try/catch block and that's it.
If you are catching an exception type, you do not need to throw it, unless you are going to rethrow it. In the example you post, the developer should have done one or another, not both.
Typically, if you are not going to do anything with the exception, you should not catch it.
The most dangerous thing you can do is catch an exception and not do anything with it.
A good discussion of when it is appropriate to throw exceptions is here
When to throw an exception?
You only need to include a throws clause on a method if the method throws a checked exception. If the method throws a runtime exception then there is no need to do so.
See here for some background on checked vs unchecked exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
If the method catches the exception and deals with it internally (as in your second example) then there is no need to include a throws clause.
The code that you looked at is not ideal. You should either:
Catch the exception and handle it;
in which case the throws is
unnecesary.
Remove the try/catch; in which case
the Exception will be handled by a
calling method.
Catch the exception, possibly
perform some action and then rethrow
the exception (not just the message)
You're correct, in that example the throws is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.
The code you posted is wrong, it should throw an Exception if is catching a specific exception in order to handler IOException but throwing not catched exceptions.
Something like:
public void method() throws Exception {
try {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
or
public void method() {
try {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
} catch(IOException e) {
System.out.println("Catching IOException");
System.out.println(e.getMessage());
} catch(Exception e) {
System.out.println("Catching any other Exceptions like NullPontException, FileNotFoundExceptioon, etc.");
System.out.println(e.getMessage());
}
}
In the example you gave, the method will never throw an IOException, therefore the declaration is wrong (but valid). My guess is that the original method threw the IOException, but it was then updated to handle the exception within but the declaration was not changed.
This is not an answer, but a comment, but I could not write a comment with a formatted code, so here is the comment.
Lets say there is
public static void main(String[] args) {
try {
// do nothing or throw a RuntimeException
throw new RuntimeException("test");
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
The output is
test
Exception in thread "main" java.lang.RuntimeException: test
at MyClass.main(MyClass.java:10)
That method does not declare any "throws" Exceptions, but throws them!
The trick is that the thrown exceptions are RuntimeExceptions (unchecked) that are not needed to be declared on the method.
It is a bit misleading for the reader of the method, since all she sees is a "throw e;" statement but no declaration of the throws exception
Now, if we have
public static void main(String[] args) throws Exception {
try {
throw new Exception("test");
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
We MUST declare the "throws" exceptions in the method otherwise we get a compiler error.

throws keyword in front of main thread

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

Handling a general exception in constructor

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.

Java: Is it possible to throws IOException once and for all?

I am new to Java. And I find it really annoying to keep writing throws IOException in the "main" and all the methods that open a file. For example:
class something{
public static void main(String[] args) throws IOException{
myobj abc = new myobj();
abc.read_file("this_file.txt");
abc.insert("text");
}
}
class myobj{
....
public void read_file(String file_loc) throws IOException{
blablabla
}
}
In this case, I have already written "throws IOException" twice. Is there a way to handle this once and for all ?
Edit:
Thanks for all the good answers. A lot of people suggested using try-catch statements.
I read about try and catch statements and I got really confused. My question is where should I carry on writing my code i.e. abc.insert("text") into the try catch statements after abc.read_file("this_file.txt") ? Should I carry on in catch block or outside it ? This is what really puzzles me.
There's no catch-all "all methods in this class throw this exception," you'll have to declare the exception on each method (e.g., read_file, etc.) or handle it within the method. This is the point of checked exceptions: To ensure that at each stage, it's clear where they may come from and where they're handled.
Note: main shouldn't throw, you should catch the exception and handle it.
Who is main throwing to? No one.
Java has checked and unchecked exceptions. Checked exceptions leave you no choice: you either have to catch them or add them to your method signature in a throws clause.
Unchecked exceptions don't require handling.
You always have the option of catching a checked exception and rethrowing it as a custom unchecked exception.
I'd write it this way:
class something{
public static void main(String[] args)
try {
myobj abc = new myobj();
abc.read_file("this_file.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class myobj{
....
public void read_file(String file_loc) throws IOException{
blablabla
}
}
I am new to Java.
Hi, I hope you enjoy your learning. Learning a new programming language effectively implies learning the idiomatic ways in which to code in that language (even the ones that we subjectively find annoying.)
This is not unique to Java. Whether you do C# or Python or C++ or Haskell, you will be bound to find something that is annoying. Then the question is, what value do you get in the effort to avoid that annoyance.
If you become more productive by avoiding the annoyance, then more power to you. Otherwise, I would follow Maya Angelou's advice: "If you don't like something, change it. If you can't change it, change your attitude."
And I find it really annoying to keep writing
throws IOException in the "main" and all the methods that open a file.
In real life development, you will be handling far more non-main exceptions that main ones (probably only one main.)
So what is the threshold, the ration of main/(all other functions) by which the annoyance is justifiable and constructive? One main and one function? One main and a dozen? One main and a hundred?
Of all the plumbing and elbow grease that needs to be done with Java, declaring exceptions on the main function is an exercise in emotion of very little use.
So take it with a grain of salt, but in my professional opinion (18 years, Java, C++, Python and a lot of other crap) is this: declare your exceptions, even on main.
Why? Because it is possible that other programs might invoke your main. That is, your Java program might be invoked from the console, or it might be embedded (invokable?) from another program.
I've done this a lot for testing or for developing systems that are embeddable. So, in this case,
you want to declare those exceptions. However, since such a program is intended for standalone and embedded use, this is the general pattern I follow (java-like pseudocode, far more simplified than real-life code):
class UtilityDelegate {
UtilitytDelegate(){ .... }
void performWork(File f) throws IOException {
// do something with file
}
}
public class SomeUtility {
public static void main(final String[] args) throws IOException {
File f = null;
try{
// do something that could throw an exception
f = new File(args[0]);
performWork(f);
} finally {
// do necessary clean-up, if any, such as closing file handles,
// sockets, flushing database changes, pray to Lord Xenu, whatever
if( f != null ){
try{
f.close();
}catch (IOException e){
e.printStackTrace(); // or use a logging mechanism or whatever
}
}
}
}
}
Now, your program can be called from the command line:
java SomeUtility myfile
Or from another java class:
public class SomeUtilityClient{
public static void main(final String[] args){
// for brevity, I'm omitting the case when the utility might
// call System.exit() itself.
try{
SomeUtility.main("a-pre-defined-filename");
} catch(IOException e){
someLog("call to utility failed, see exception", e);
System.exit(-1);
}
System.exit(0);
}
}
An argument could be made that such a java client should call the embedded program via another method name, not main. That is fair, and in many cases, it is the better approach.
But just consider this one reason or approach of why to declare your exceptions everywhere, even on your main.
The main method doesn't need to throw anything.
class something{
public static void main(String[] args)
try {
myobj abc = new myobj();
abc.read_file("this_file.txt");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
I know you may find this language feature annoying but trust me, it is far less frustrating than managing code which does not propagate exceptions. You spend hours and hours wondering why your code is not doing something and then you stumble across this:
try {
doSomethingImportant();
}
catch(Exception e) {
// Nah can't be bothered
}
Simply put, no.
There are two ways to deal with exceptions:
You either handle that exception in your current method (main in your case) by surrounding the API that throws the exception with try-catch and writing code in the catch block to handle it OR
Add "throws IOException" on the method signature in which case you force the callers of your method to deal with it.

Java Unreported Exception in ADT

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 :))

Categories