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 :))
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.
Some 3rd party library swallowed an Exception:
String getAnswer(){
try{
// do stuff, modify instance state, maybe throw some exceptions
// ...
return computeAnswer();
}catch (SomeException e){
return null;
}
}
As much as I want to change it into:
String getAnswer() throws SomeException{
// do stuff, modify instance state, maybe throw some exceptions
// ...
return computeAnswer();
}
I can't, because the library is already packaged into a jar. So, is there a way to bring the exception back?
I don't need to rethrow, a stacktrace with exception and message would work too.
I don't think reflection would help here, Unsafe perhaps?
Yes I know I can use a debugger to find out what's happening, but that wouldn't be very useful if I need the exception at runtime for logging and stuff like that
You can do it without reflection or AOP. The main idea is to throw another (unchecked) exception in the constructor of SomeException. There are some limitations (see at the end of this answer) but I hope it fits your needs.
You need to replace the SomeException with a new version (just create a SomeException.java file in the original package but in your src directory) with something like :
package com.3rdpartylibrary;
public class SomeException extends Exception {
public static class SomeExceptionWrapperException extends RuntimeException {
public SomeExceptionWrapperException(final SomeException ex) {
super(ex.getMessage(), ex);
}
}
public SomeException(final String message) {
super(message);
throw new SomeExceptionWrapperException(this); //<=== the key is here
}
}
The SomeExceptionWrapperException has to be unchecked (inherit from RuntimeException or Error). It will be our wrapper to carry the SomeException accross the ugly 3rd party catch(...)
Then you can catch the SomeExceptionWrapperException in your code (and eventually rethrow the original SomeException:
//original, unmodifiable 3rdParty code, here as a example
public String getAnswer() {
try {
//some code
throw new SomeException("a message");
} catch (final SomeException e) {
return null;
}
}
//a wrapper to getAnswer to unwrapp the `SomeException`
public String getAnswerWrapped() throws SomeException {
try {
return getAnswer();
} catch (final SomeExceptionWrapperException e) {
throw (SomeException) e.getCause();
}
}
#Test(expected = SomeException.class)
public void testThrow() throws SomeException {
final String t = getAnswerWrapped();
}
The test will be green as the original SomeException, will be thrown.
Limitations:
This solution will not work if either :
if SomeException is in java.lang as you cannot replace java.lang classes (or see Replacing java class?)
if the 3rd party method has a catch(Throwable e) (which will be horrible and should motivate you to ignore the full 3rd party library)
To solve this based on your constraints I would use aspects (something like AspectJ) and attach it to the creation of your exception, logging (or having it call some arbitrary) method then.
http://www.ibm.com/developerworks/library/j-aspectj/
If all you're looking for is to log the stacktrace + exception message, you could do that at the point you're throwing your exception.
See Get current stack trace in Java to get the stack trace. You can simply use Throwable.getMessage() to get the message and write it out.
But if you need the actual Exception within your code, you could try and add the exception into a ThreadLocal.
To do this, you would need a class like this that can store the exception:
package threadLocalExample;
public class ExceptionKeeper
{
private static ThreadLocal<Exception> threadLocalKeeper = new ThreadLocal<Exception>();
public static Exception getException()
{
return threadLocalKeeper.get();
}
public static void setException(Exception e)
{
threadLocalKeeper.set(e);
}
public static void clearException()
{
threadLocalKeeper.set(null);
}
}
... then in your code which throws the Exception, the code that the 3rd party library calls, you can do something like this to record the exception before you throw it:
package threadLocalExample;
public class ExceptionThrower
{
public ExceptionThrower()
{
super();
}
public void doSomethingInYourCode() throws SomeException
{
boolean someBadThing = true;
if (someBadThing)
{
// this is bad, need to throw an exception!
SomeException e = new SomeException("Message Text");
// but first, store it in a ThreadLocal because that 3rd party
// library I use eats it
ExceptionKeeper.setException(e);
// Throw the exception anyway - hopefully the library will be fixed
throw e;
}
}
}
... then in your overall code, the one that calls the third party library, it can setup and use the ThreadLocal class like this:
package threadLocalExample;
import thirdpartylibrary.ExceptionEater;
public class MainPartOfTheProgram
{
public static void main(String[] args)
{
// call the 3rd party library function that eats exceptions
// but first, prepare the exception keeper - clear out any data it may have
// (may not need to, but good measure)
ExceptionKeeper.clearException();
try
{
// now call the exception eater. It will eat the exception, but the ExceptionKeeper
// will have it
ExceptionEater exEater = new ExceptionEater();
exEater.callSomeThirdPartyLibraryFunction();
// check the ExceptionKeeper for the exception
Exception ex = ExceptionKeeper.getException();
if (ex != null)
{
System.out.println("Aha! The library ate my exception, but I found it");
}
}
finally
{
// Wipe out any data in the ExceptionKeeper. ThreadLocals are real good
// ways of creating memory leaks, and you would want to start from scratch
// next time anyway.
ExceptionKeeper.clearException();
}
}
}
Beware of ThreadLocals. They have their use, but they are a great way of creating memory leaks. So if your application has a lot of threads that would execute this code, be sure to look at the memory footprint and make sure the ThreadLocals aren't taking up too much memory. Being sure to clear out the ThreadLocal's data when you know you no longer need it should prevent that.
JVMTI agent can help. See the related question.
I've made an agent that calls Throwable.printStackTrace() for every thrown exception, but you may easily change the callback to invoke any other Java method.
A rather dirty trick that could do the job with less effort than AOP or de-/recompile the JAR:
If you can copy the source code, you can create a patched version of the class in question with your version of the getAnswer method. Then put it on your classpath before the third party library that contains the unwanted version of getAnswer.
Problems could arise if SomeException is not a RuntimeException and other third party code calls getAnswer. In this situation I am not sure how the resulting behavior will be. But you could circumvent this by wrapping SomeException in a custom RuntimeException.
Could you not just use a reference variable to call that method, if the result is a null, then you can just display a message/call an exception, whatever you want?
if you're using maven, you would exclude packages of the library.
Dependency Exclusions.
I hope to be helpful
If you have the source to the throwing class, you can add it "in the original package but in your src directory" using the technique as #BenoƮt has pointed out. Then just change
return null;
to
return e;
or
e.printStackTrace();
etc.
This would be quicker then making a new Exception.
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
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.
I'm new to the Java scene but currently working on an assigned assessment. I'm wondering if there is a way to catch an exception inside a class function and throw another exception so the function that called the class function doesn't need to know about the first exception thrown.
For example
public void foo() throws MasterException {
try {
int a = bar();
} catch (MasterException e) {
//do stuff
}
}
public void bar() throws MasterException, MinorException {
try {
int a = 1;
} catch (MinorException e) {
throw new MasterException();
}
}
I hope this example explains what I'm trying to achieve. Basically I want the calling function not to know about MinorException.
Remove , MinorException from the declaration of bar and you are done.
I would also do:
throw new MasterException(e);
If MasterException had a constructor that supported it (its standard it does, the Exception class do).
Absolutely. You want to change this line:
public void bar() throws MasterException, MinorException
to this:
public void bar() throws MasterException
Everything else should work exactly how you've written it.
Just remove the MinorException from throws clause of bar().
I would remove MasterException from foo() as you are catching it and as the other answers say, MinorException from bar().
Additionally, in case MasterException or MinorException is a subclass of RuntimeException, you do not need to declare it. See e.g. http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Remove throws MasterException from the declaration of method foo(), the reason is clear that the MasterException has been ready catched SO would not get occurred anyway.
Remove , MinorException from the declaration of method bar().