File Layout Exception - java

I'm writing a java Application that can open and edit files. But I want it to give me an error if the layout of the file isnt as it should be.
My file looks like this:
Title
X Y
Name
X times line
If looked into try and catch but that doesnt give me the right solution to give an error like:
"There is no X or Y specified"
or
"There is nog Title in this file"
Whats the option to do this?

Create your own Exception class that extends Exception. This is sometimes called a domain exception, because it's one that only applies to your problem domain.
Here's an example of how you would code it:
public class FileLayoutException extends Exception {
// extending Exception means you can throw it and declare it to be thrown
}
Declare your method to throw it:
public void readFile() throws FileLayoutException {
// some impl
}
Then use it like this when you detect a problem:
throw new FileLayoutException("There is no X or Y specified");
or
throw new FileLayoutException("There is no Title in this file");
Because your error conditions are "file-related", you may consider extending IOException instead of Exception

Related

How do I create an if statement in Java that throws an error if the sum of two text fields is greater than another textfield

I am pretty new to Java and I have three text fields which are all integers in my Java project.
I want to create an if statement that throws an error if the sum of values in text field 1 and 2 are greater than textfield 3.
This is what I was able to come up with
if (text3.getText() > (text1.getText()+text2.getText())){
System.out.println(“Error”)
}
Do I need to put it in a try and catch statement?
You can create yourself a new Exception Class:
public class NumberExceededException extends Exception {
public NumberExceededException(String exceptionMessage){
super(exceptionMessage);
}
}
Then use it with:
If (text3.getText() > (text1.getText()+text2.getText())) {
throw new NumberExceededException("You have exceeded my expectations");
}
This will throw a new bubbling exception which can be caught by a try catch higher up.
Just to note that this is not exclusive to Netbeans it is a Java function, Netbeans is an IDE and only outputs whatever the JVM tells it to output.

How to implement wrapper for multiple exceptions?

I've some modules, each containing some models what I want to parse from persisted file(s).
When I read a file I don't know which module will be able to parse it, that's why I try to parse it with my first module's parser. If that fails I try with the parser of the second module and continue that until I've tried all my parsers.
The parsers can give back information in form of multiple exceptions (different subtypes of Exception class) or the parsed model object (different subtypes of a ModelBase class).
If none of the parsers succeed I want to wrap all of given exceptions into one big Exception, throw it and catch it somewhere in my application code (in form of a new big exception), where I can handle the problem (e.g. show all the parsing problems and stacktraces to the user, handle them somehow etc.).
My pseudocode:
ModelBase getModelOrBigException(File file)
throws MyBigException {
List<Exception> exceptions = new ArrayList<>();
for (Module module : myModules){
try {
ModelBase model = module.parse(file);
return model;
}
catch (ParsingException1 p1) { exceptions.add(p1); }
catch (ParsingException2 p2) { exceptions.add(p2); }
}
throw new MyBigException(exceptions);
}
I want to call the code
void openFilesHandler(){
//... selecting file
try {
process(getModelOrBigException(file));
} catch (MyBigException e) {
// process the sub-exceptions or show them to user or print stacktraces of all sub-exceptions or show sub-exceptions by type etc
}
}
Obviously if I catch MyBigException I won't be able to call methods like getStackTrace(), getMessage(), getLocalizedMessage() on them by default, only if I implement my exception class similar to this:
class MyBigException extends Exception {
public MyBigException(Exception e1, Exception e2, ..., Exception eN){
super(e1, e2, ..., eN); // This is not possible, only one argument is acceptable
}
}
or to this:
class MyBigException extends Exception {
List<Exception> exceptions = new ArrayList<>();
public MyBigException(List<Exception> exceptions){
super(exceptions); // This is not possible, list or array of exceptions is not allowed here
}
}
Questions:
How should I create a new type of Exception, which can store multiple exceptions with support of the original Exception class's methods?
When I do this:
myBigException.printStackTrace();
or this:
myBigException.getMessage();
I want to print/get all stacktraces of all stored exceptions.
Should I pass all given exceptions to super() method?
Is there any better way to do the parsing solution better than the solution above?
I want to print/get all stacktraces of all stored exceptions. Should I
pass all given exceptions to super() method?
If you wanted to print all stacktraces or exception messages, you are almost there and you need add few more bits as explained below:
(1) Inside MyBigException, create a constructor MyBigException(List<Exception> exceptions, String exeptionMessage) and call super(exeptionMessage);
(2) override printStackTrace() in your MyBigException and iterateover the List<Exception> and call printStackTrace() on each exception object.
You can refer the below code on the same:
MyBigException class:
public class MyBigException extends Exception {
private List<Exception> exceptions = new ArrayList<>();
public MyBigException(List<Exception> exceptions, String exeptionMessages){
//call super and pass message
super(exeptionMessages);
this.exceptions = exceptions;
}
public void printStackTrace() {
for(Exception exception : exceptions) {
exception.printStackTrace();
}
}
}
getModelOrBigException() code:
ModelBase getModelOrBigException(File file)
throws MyBigException {
List<Exception> exceptions = new ArrayList<>();
//Capture exception messages as well using StringBuilder
StringBuilder exceptioMessages = new StringBuilder();
for (Module module : myModules){
try {
ModelBase model = module.parse(file);
return model;
}
catch (ParsingException1 p1) {
exceptions.add(p1);
exceptioMessages.append("YOUR MESSAGE FOR ParsingException1;");
}
catch (ParsingException2 p2) {
exceptions.add(p2);
exceptioMessages.append("YOUR MESSAGE FOR ParsingException2;");
}
}
throw new MyBigException(exceptions, exceptioMessages.toString());
}
Two options come to my mind.
suppressing the given exceptions using addSuppressed. You can then retrieve it again later using getSuppressed(). This is also the mechanism which is used on try-with-resources-statements throwing exceptions. This way the stack trace of your myBigException also shows the suppressed ones automatically.
add an accessor method to your exception classes internal list so you can access it from outside, e.g. getExceptions(). Here however you need to handle the stack trace of each exception yourself. You can overwrite the printStackTrace(*) methods, but that seems overhead to me.
It mainly depends on what you want to achieve (or what is more appropriate) and how you want to access the exceptions later on.
You may also want to supply your own printStackTraces() method in the second case or overwrite the getMessage()-method in both cases to supply a message that is more appropriate.
You can't have many exceptions as the cause of your BigException. One exception is thrown and it goes up the stack until you handle it. You could add it to a causality relation chain, and that's why Exception's constructor accepts another exception as the cause of this exception.
But in your case, you are throwing the BigException after many parsing exceptions have been thrown and already handled (by adding them to a list).
So your first exception in the chain is actually BigException. If I were you, I would just have a getter for the list of parsing exceptions and work with that list, i.e. to inform the user, log the list etc.

Where to check for values and throw an exception

Let's say I have a class like the following one:
public class Parameter {
private double[] parameterValues;
public Parameter(double[] parameterValues) throws BadElementInitializationException {
checkParameterValues(parameterValues);
this.parameterValues = parameterValues;
}
public double[] getParameterValues() {
return parameterValues;
}
public void setParameterValues(double[] parameterValues) throws BadElementInitializationException {
checkParameterValues(parameterValues);
this.parameterValues = parameterValues;
}
private void checkParameterValues(double[] parameterValues) throws BadElementInitializationException {
if(parameterValues == null)
throw new BadElementInitializationException("Parameter values cannot be null");
if(parameterValues.length == 0)
throw new BadElementInitializationException("Parameter values cannot be empty");
}
public int noOfValues(){
return parameterValues.length;
}
}
And the array is later used to perform some calculations.
My question is, where should I check that parameterValues is not null, nor empty? Should I do that in the Parameter class, like I did, or should I do that in the class which performs calculations?
Moreover, should I throw an exception here, or in the Calculation class? And what would be the reason to throw checked and what to throw unchecked exception? My goal is to make a stable application that won't crash easily.
You should do it in all places where getting an null or empty array is not valid. If you do it just in your Parameter class and rely on this having done the check in your Calculator class, then what if you start to use your Calculator class somewhere else? Who are you going to rely on to do the checks there? If you do it in the Calculator class and then refactor the Parameters class to use something else in the future, then your check will go away.
If its also invalid to have a null or empty array in your Calculator class then you need to check there as well.
Alternatively pass an object to both which cannot be empty and then you only need to make the null check.
Should I do that in the Parameter class, like I did, or should I do
that in the class which performs calculations?
In my opinion, better to check in Parameter class then any other classes. You could see how it do in google guava , for example, in most class they use:
public static boolean isPowerOfTwo(BigInteger x) {
checkNotNull(x);
return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1;
}
or
public static int log2(BigInteger x, RoundingMode mode) {
checkPositive("x", checkNotNull(x));
...
Moreover, should I throw an exception here, or in the Calculation
class?
If you check your parameters in Parameter class, better throw in Parameter class also. In addition to, you may use some standart function to check and throw exception, for example from google guava:
com.google.common.base.Preconditions.checkNotNull
com.google.common.base.Preconditions.checkArgument
com.google.common.math.MathPreconditions.checkPositive
And what would be the reason to throw checked and what to throw
unchecked exception?
A checked exception is good if you think that you must catch and working this exception later. In most case, for wrong parameters quite enough unchecked exception, like standart IllegalArgumentException in Java. Also, a checked exception need to say other programmers (who use this API) that this exception could be happened, and they need to working with it. Working with an unchecked exception is quite easy for programmer (and often reduce your source code), however a checked exception become your code is more reliable.
A more info about checked and uncheked exceptions, you could find in this post

Error with java FileInputStream and FileOutputStream

I just made my first I/O based stuff in Java.
I want to check if the content written to a file is properly saved in, or not.
For which i wrote the following code..
import java.io.*;
public class check implements Serializable {
//Make two variables and methods to initialise them
private int height;
private int width;
public void setWidth(int w){
width = w;
}
public void setHeight(int h){
height = h;
}
public static void main(String[] args) {
check obj = new check();
obj.setHeight(20);
obj.setWidth(30);
try{
FileOutputStream fs = new FileOutputStream("foo.txt");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(obj);
os.close();
}
catch(IOException ex){
}
//We set them to null so we can't access the objects on heap.
obj = null;
//Now we read them back from file
try{
ObjectInputStream is = new ObjectInputStream(new FileInputStream("foo.txt"));
check stored = (check) is.readObject();
//Check to see if it worked.
System.out.println("Variable, stored contains.." + stored.getType());
}
catch(IOException ex){
}
}
}
But it produces the following error.
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
at check.Check.main(Check.java:33)
Anyone got any idea to solve the issue?
Take a look at http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#readObject(). The method lists a couple of exceptions. For every exception listed that is not a sub-class of RuntimeException you need to either catch the exception or declare that the method can throw that exception. You have only done this for IOException. You also need to do this for the other exceptions listed in the documentation. This needs to be done for all methods that throw non-runtime exceptions.
Your IDE is letting you run some code even though you are missing some classes or despite having compilation errors. Fix the compilation errors before you run them.
Your code is uncompilable at the moment. Line 36 fails.
System.out.println("Variable, stored contains.." + stored.getType());
This is because the class check does not contain a method getType(). Maybe You meant something along the lines of getClass().getName()?
Fix this error and try again. Your own error message does not make sense to me - is it generated by an IDE?
PS. Have a look at Java coding conventions regarding the naming of classes, variables and such. :)

How to show full stack trace on eclipse?

I'm using Eclipse to debug a Java application. Somewhere in the code I get an exception and the stack trace:
Caused by: java.io.EOFException: The connection has been reset while reading the header
at com.gemstone.gemfire.internal.cache.tier.sockets.Message.fetchHeader(Message.java:583)
at com.gemstone.gemfire.internal.cache.tier.sockets.Message.readHeaderAndPayload(Message.java:599)
at com.gemstone.gemfire.internal.cache.tier.sockets.Message.read(Message.java:542)
at com.gemstone.gemfire.internal.cache.tier.sockets.Message.recv(Message.java:1029)
at com.gemstone.gemfire.cache.client.internal.AbstractOp.attemptReadResponse(AbstractOp.java:158)
at com.gemstone.gemfire.cache.client.internal.AbstractOp.attempt(AbstractOp.java:363)
at com.gemstone.gemfire.cache.client.internal.ConnectionImpl.execute(ConnectionImpl.java:229)
at com.gemstone.gemfire.cache.client.internal.pooling.PooledConnection.execute(PooledConnection.java:321)
at com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.executeWithPossibleReAuthentication(OpExecutorImpl.java:646)
at com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.execute(OpExecutorImpl.java:108)
... 11 more
How do I get the whole stack instead of the ... 11 more?
You have the entire stack.
This is only part of a stack trace. Directly before this was another piece. Look at the bottom lines of this one, and the top lines of the previous one. You'll see them match up. The stack trace began with a section that doesn't begin with "Caused by".
The "Caused by" exception is hiding parts of the stack trace that are verbatim copies of stack trace entries in its parent. In other words, Java doesn't show the entire stack up to main() for every cause - it just shows what you haven't seen already. See the Throwable.printStackTrace() documentation.
The "Caused by" is filled when you provide a cause when creating a Throwable. Look at the constructors for it. This is done when a piece of code catches a low-level exception and then wants to rethrow it as a different exception class.
the answers above are not accurate, every time the stack show the words "caused by" it means that the exception went through one or multiple methods until it was caught, and then thrown again. This could happen many many many times, the stack trace is not a loop, it is a single direction, so no, the stuff at the top does not relate to the stuff at the bottom, the most important part IS at the bottom, that is the root of the exception, so if you would have:
Exception in class main: blah blah blah
...lines of code...
caused by FileNotFoundException
...lines of code...
caused by: MalformedURLException
...lines of code...
caused by: NullPointerException
then you would not want to focus so much on the FileNotFoundException, but you would want to focus more on the NullPointerException. Like say you had a properties file with a file name in it. If accidentally used mykey, to find the property "myKey", then the propertiesResource would return a null, that would then get thrown all the way through all the lines of code (hopefully) to your application where the last catch block is. . . wich, at this piont, it would be "wrapped" not as a nullException, but as a FileNotFoundException. . .
We might be diverging from the actual problem he's facing. I was having similar problem and it turns out I had my Limit console out put box check marked. After I removed it I was able to see the full stack trace.
Steps:
Right click on console || ctrl + click if mac
go to preferences and follow the above instructions
I think it means that the Exception was caught and packaged into another 11 times before printStackTrace was called.
Try and figure out the output of the following program for better understanding:
public class PrintStackTrace {
public static void main(String[] args) {
try {
level1();
} catch (Exception e) {
e.printStackTrace();
}
try {
level2();
} catch (Exception e) {
e.printStackTrace();
}
}
static void level2() throws Exception {
try {
level1();
} catch (Exception e) {
throw new Exception(e);
}
}
static void level1() throws Exception {
try {
throwingMethod();
} catch (Exception e) {
throw new Exception(e);
}
}
static void throwingMethod() throws Exception {
throw new Exception("throwingMethod");
}
}
As Ed says, it is showing the entire stack, but leaving out information that you've already seen. See Throwable#printStackTrace()
Quoting from there:
Note the presence of lines containing the characters "...". These
lines indicate that the remainder of the stack trace for this
exception matches the indicated number of frames from the bottom of
the stack trace of the exception that was caused by this exception
(the "enclosing" exception). This shorthand can greatly reduce the
length of the output in the common case where a wrapped exception is
thrown from same method as the "causative exception" is caught
Often an exception is wrapped; created with another exception as the cause:
try {
// something which causes an Exception
} catch (Exception e) {
throw new SpecificException("help", e);
}
In this case, displaying the stacktrace will create the ... 11 more that you see.
I have never seen that, but try this
public void problemFunction(){
try{
//your code
catch(Exception ex){
ex.printStackTrace();
}
}
or
public void problemFunction(){
try{
//your code
}
catch(Exception ex){
System.out.println(ex);
StackTraceElement[] arr = ex.getStackTrace();
for(int i=0; i<arr.length; i++){
System.out.println(arr[i].toString());
}
}
}
There is a vmargs option
-XX:-OmitStackTraceInFastThrow
which might help in some situations.
To simplify the accepted answer let us consider a simple notation.
Exception in main ……
At A
At B
At C
Caused by ….
AT P
At Q
AT R
AT A - > { THIS ONE IS REPEATED , But slightly with line
number changes } .
MISSING 2 MORE { THOSE 2 ARE NOTHING BUT B AND C .}
Caused by …
At X
At Y
At P - > { THIS ONE IS REPEATED , But slightly line
number changes }
Missing 5 More ( Those 5 are nothing but Q,R, ,A,B,C )
Hence you have the entire stack.
But MAKE SURE CHECK BOX FOR “limit console output” is NOT checked under run/debug drop down --> console in eclipse preferences.
You can use the following code to get more clarity.
try {
// code causing exception
}
catch(Exception ex){
Throwable exThrowable=ex;
while(exThrowable!=null) {
System.out.println(exThrowable);
StackTraceElement[] arr =
exThrowable.getStackTrace();
for(int i=0; i<arr.length; i++){
System.out.println(arr[i].toString());
}
exThrowable=exThrowable.getCause();
}

Categories

Resources