Issues with learning try/catch - java

I'm currently in a java course and trying to learn how to catch exceptions. In this case I have an input file that is only allowed to contain certains signs and must contain a goal and a start. I check all this in a seperate class constructor and want to insted of just telling the user something is wrong use a try/catch to tell the user that he did something wrong.
while(scanner.hasNext()){
temp = scanner.nextLine();
try {
testString(temp);
}
catch (/*Don't know what to catch*/){
System.out.println("Input file contains unvalid input");
}
mazeData.add(row, temp);
row++;
}
try{
containStartAndGoal();
}
catch(/*Dont know what to catch?*/){
System.out.println("Input file have either no goal or start!");
}
Currently this is my issue, i have tried to use a IOExecption but that does not seem to work. If I use just Execption i need to catch it every time i try to call this method. Which I do in both my test program and main program. I have tried to read as much as I can around here but don't seem to understand what I am suppose to do. Can I not try something if I don't throw it somewhere else? And what type of execption am I suppose to use when there is an input file that is incorrect. We didn't really get any information around how these work in school only that they exist.

Related

Java. Try to deserialize if file exists. Otherwise just don't

I am using Serialization to get persistent storage for my library managing app (I know it is not the right way, but it's the way my professor wants it).
I am using the following code inside my main();
controlador.getBiblioteca().getGestorMaterial().setListaLibros((Modelo.ColeccionLibros) controlador.getSerializador().abrirArchivo("libros.dat"));
My Serializador class has the abrirArchivo("FileName.dat") function (openFile in English).
That function looks like this:
public Object abrirArchivo(String nombreDelArchivo) {
Object retorno = null;
try {
lectorArchivos = new ObjectInputStream(new FileInputStream(
nombreDelArchivo));
retorno = lectorArchivos.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return retorno;
}
Now I am trying to check if the program gets a FileNotFoundException for any of the files. If it does, it should just not deserialize the file and go for the next one: that would just mean there is no book in my library yet.
The problem is, if the line runs, it seems to set my book list using setListaLibros() to null. And whenever I try to access that list, i get a NullPointerException. The list was already initialized as an empty list though, so I just need to leave it alone as long as the "libros.dat" file is not found.
What is the right way to get that done?
I don't know if I understand the problem well. However, as I can see in your code, when an exception FileNotFoundException happens, "retorno" will keep null. That's the reason why you get setListaLibros(null).
And then your list will became null. If you don't want that behavior, you should initialize "retorno" with an empty list instead of null.
You could add a line before this: controlador.getBiblioteca().getGestorMaterial().setListaLibros((Modelo.ColeccionLibros) controlador.getSerializador().abrirArchivo("libros.dat")); which checks if the file exists. If it does not, then it prompts the user. This way, the user knows something went wrong and can act accordingly.
Alternatively, you can make a change in your setListLibros method wherein, if the argument passed is null, then you do not do any assignment.
Personally, I would go with the first option.
As a side note, please break down your code, something like so: controlador.getBiblioteca().getGestorMaterial().setListaLibros((Modelo.ColeccionLibros) controlador.getSerializador().abrirArchivo("libros.dat")) can get hard to read and debug.
There is an aspect that the other answers are not mentioning: why are there no serialized objects when your library is empty?!
What I mean is: you could distinguish between "program runs the first time" (and obviously no serialized data exists) or "program ran before; and thus it fully configures itself from serialized data.
Meaning: "being empty" can be a valid state of a library, too. So another option would be to not use a "special value" (aka "no file with data") to represent that information ... but (de)serialize an empty list.
You could check if the file exist like:
String fileName;
File f1 = new File(fileName);
if (f1.exists()) {
//Do the work
}

try catch finally understanding check

I've found this subject very confusing was wondering if i could get some feedback to see if I understand this concept.
if you do something like
int x = "this is not an int"
java will complain and throw a crash error when you try to run it, in this case "static error". so if
I wanted to create a exception handler for this it would be something like this?
try
{
int x = "this is not an int"
}catch(Staticerror nameIcanMakeUp){
x = 4}
finally{
does the x has to be set to a acceptable value in the catch to prevent a crash?
does the first argument of catch have to be the same as what java would say when it crashes?
do I put the rest of the code in the finally block should I have more code after the bit of code that might throw exceptions?
also how would I do this with a exception I want to define like if its an age field and I don't want people entering dates from the future etc?
if you do something like int x = "this is not an int" java will complain
Java is a statically typed language so it picks up these error at compile time, not when you run the program.
and throw a crash error when you try to run it,
Actually the javac compiler gives you the error.
I wanted to create a exception handler for this it would be something like this?
There is no way to ignore code which doesn't compile at runtime as you can't run a program which didn't compile.
What you can do is something like this.
Object o = "This is not an Integer";
Integer i = (Integer) o;
This does compile and produces a runtime rather than a compile time error. You can catch this with
Object o = "This is not an Integer";
try {
Integer i = (Integer) o;
} catch(ClassCastException cce) {
cce.printStackTrace();
}
does the x has to be set to a acceptable value in the catch to prevent a crash?
The code in the catch block also has to compile and run without throwing an Exception.
does the first argument of catch have to be the same as what java would say when it crashes?
The class you try to catch has to be the class of the exception or a super class.
do I put the rest of the code in the finally block
It depends, but usually you don't need a finally block.
should I have more code after the bit of code that might throw exceptions?
It depends on what you are trying to do but usually you put as little in this block as possible.
also how would I do this with a exception I want to define like if its an age field and I don't want people entering dates from the future etc?
You can create you own custom Exception by extending an existing one, but I tend to re-use the existing ones like
if (age < 0)
throw new IllegalArgumentException("Age cannot be negative");

NoSuchElementException when using do while loop

I'm working on my College project and I keep getting this exception when I try to make all my code loop. When not in a loop it works perfectly fine, it includes creating text files and appending text files (if thats any help). My assumption is that my scanner is causing these problems, but I don't know what the problem is or how to fix it.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at PDispenser_V1.main(PDispenser_V1.java:51)
I can't post my code because plagiarism software checks stackoverflow and my full project will be plagiarised if I do. I know that's a huge downfall but if you could tell me what to look for in general and how to fix it (provided I gave you enough to go on) that would be great! Also the only line number the complier gave me that exists is 51 and it has this code on it.
selection = input.nextInt();
This line is followed by a switch statement with a bunch of methods in each case. If theres anything I can answer without showing any code please ask. Any help is appreciated.
EDIT: I should also say, it complies fine but when I go to select one of the options again thats when it throws the exception.
EDIT2: I should also mention that the selection is taking a line from the user not a file.
You are probably using nextInt without checking if there is one available to read on the stream, as the javadoc for nextInt says:
Throws:
NoSuchElementException - if input is exhausted
Try using hasNextInt() to check if there is an int before attempting to read one from the stream.
Exception is throwing because, there is no next token for the input to return.
To avoid such exceptions it is always best practice to first check the existence of next token using input.hasNextInt() . If it returns true then extract the next token using input.nextInt(). Example.
if (input.hasNextInt())
{
int i = input.nextInt();
}
EDIT
This Error can be produced in following way:
public class Scanned
{
public static void main(String st[])
{
Scanner input = null;
try
{
InputStream in = System.in;
input = new Scanner (in);
while (true)
{
System.out.println(input.nextInt());
in.close();
}
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
Make sure that the InputStream is not closed within the loop.

Handle the Exception and Continue the process without termination in java

I am working on java, I read huge no.of XML files & insert them into ORACLE database but while inserting I am getting Exception, Then my program terminates without processing remaining records, Could any one please help me out from this situation, I want to read the files until unless they finished without termination of program while exception occurs.
for (File f : myFileArray) { //Or whatever you have
try {
// your code which might throw exception
} catch ( <Your exception name here> e) {
System.err.println("File failed: " + f.getAbsoultePath() );
continue; //if more code follows the try catch block, otherwise omit it
}
}
Since you did not gave any code snippet for what you actually do, I tried a guess.
As the comments suggest, you use try/catch-Blocks for handling exceptions in Java.
A good tutorial is imho
http://chortle.ccsu.edu/java5/index.html
Chapter 80 and 81.

J2ME converter program not accepting user's input

I am having problems with my converter program not accepting the value the user inputs. Everything seems so right but the result is always as if the user entered nothing. If anyone can just point me in the right direction I would greatly appreciate it!
my project consists of 2 files (1 midlet and 1 class).
code was too long to post on this forum so I uploaded the zip.
Edit hosted here now should be cleaner: removed
I can't really narrow it down to a small piece of code because it could be any number of things which I have already tried. I know its asking quite a bit but the code isn't insanely long. I'd be extremely grateful if anyone could take a look.
edit 2: the file seems to be trying to download an image... here is the code in another forum i posted in but got no answers.: http://www.codingforums.com/showthread.php?p=1024059#post1024059
edit 3: here is where I think the problem lies in the code:` public double customForm (String fName)
{
ui_form = new Form(fName);
ui_form.addCommand(Convert);
ui_form.addCommand(Back);
display.setCurrent(ui_form);
num = new TextField("Enter the number of units you would like to convert", "", MAX_CHARS, TextField.ANY);
ui_form.append(num);
ui_form.setCommandListener(this);
/***********************/
/* THIS IS NOT WORKING*/
// str = num.getString();
str = "The number is: " + num.getString();
try
{
numUnits = Double.parseDouble(str);
}
catch (NumberFormatException nfe)
{
}
finally
{
return numUnits;
}
//return str;
}
`
but you will probably need to look at the rest of the code to see where the problem lies. this is just the root i think
You cannot read the text field right after it has been added to a form. It looks like you assumed the num.getString() method to block until there's user input - this is not the case. User input is provided asynchronously, i.e. you should read the text field's content in response to a user command, somewhere in the commandAction() method (in your case when the Convert command has been issued by the user).
Handling user events asynchronously is a core pattern in GUI development. In this regard I recommend to read some example code for command handling in JavaME, for instance this or this.

Categories