Error handling when the input line exceeds 50 characters in Java - java

I have a program that reads from a txt file each line and I'm supposed to handle the error when the line has more than 50 characters. I'm not very familiar with exceptions in Java, but is it ok if I just use an 'if' condition like this:
if(line.length() > 50) {
System.out.println("over 50 characters on this line");
return;
}
or should I declare a function like this:
static void checkLineLength(int lineLength) {
if(lineLength > 50) {
throw new ArithmeticException("over 50 characters");
}
}
and call it inside the main function?
checkLineLength(line.length());
LE: I've changed the exception handling block a bit:
static void checkLineLength(int lineLength) {
if(lineLength > 50) {
try {
throw new Exception("over 50 ch");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
}
}
Is it better? I see it works but I want to know if it's the professional way to do it.

The other answers so far concentrate on throwing and handling exceptions (with very good advice), but don't discuss the point whether exceptions are the best way of handling the long-text-line situation.
You write:
I'm supposed to handle the error when the line has more than 50
characters.
The wording "handle the error" needs interpretation / clarification. What are you supposed to do if a single line from the text file exceeds the 50-characters limit?
Use the first 50 characters and silently ignore the trailing rest?
Ignore the single line as faulty, but read the other lines?
Abort the whole file as unreadable because of syntax error, but keep the program running, e.g. to allow the user to select a different file?
Abort the whole program?
Depending on the answer to this question, exceptions might or might not be the answer for your problem.
Let's suppose, the method we talk about looks like this:
public List<FancyObject> readFromTextFile(File file) { ... }
It reads the text file line by line and puts one FancyObject per line into the result List.
In Java, a method can only either return a result or throw an exception. So in the first and second case, where you want to get a result (at least from the short lines), you can't throw an exception.
In the third case, I'd recommend to throw an exception as soon as you find a line longer than 50 characters (just as eddySoft suggested).
Even in the fourth case, I wouldn't put the System.exit() into the readFromTextFile() method, but in some higher-level method that's responsible for controlling the whole application, e.g. main(). It's a matter of readability or "principle of least surprise". Nobody expects a method named readFromTextFile() to be able to completely abort the Java Virtual machine. So, even in this case, I'd have the method throw its LineLimitException, and have main() catch that, inform the user and do the System.exit().

As long as you throw an Exception, both the approaches are fine. Only advantage while writing the method is you can reuse it.
Just one thing, System.out.println("over 50 characters on this line"); will log this in the console and silently move forward.
Throwing some exception like throw new ArithmeticException("over 50 characters"); , will break the flow.
EDIT:
METHOD 1:
You can use this piece of code:
static void checkLineLength(int lineLength) {
if(lineLength > 50) {
throw new ArithmeticException("over 50 characters");
}
}
OR
METHOD 2:
static void checkLineLength(int lineLength) {
if(lineLength > 50) {
throw new ArithmeticException("over 50 characters");
}
}
and call this method from somewhere in your code and put it in a try block:
try{
checkLineLength(line.length()); // call to the method
}
catch(Exception e){
e.printStackTrace(); // print the stacktrace if exception occurs
System.exit(1);
}

Define your Exception class. Example
class LineLimitException extends RuntimeException{
public LineLimitException(String message){
super(message);
}
}
Use your exception class in your logic
if(lineLength > 50) {
throw new LineLimitException("over 50 characters");
}

Related

How to convert string to integer with parseInt?

I have this code:
public static void main(String[] args) {
List<Valtozas> lista = new ArrayList<Valtozas>();
try {
File fajl = new File("c://data//uzemanyag.txt");
Scanner szkenner = new Scanner(fajl, "UTF8");
while (szkenner.hasNext()) {
String sor = szkenner.nextLine();
String [] darabok = sor.split(";");
String szoveg = darabok[0];
Valtozas valtozas = new Valtozas(Integer.valueOf(darabok[0]), Integer.valueOf(darabok[1]), Integer.valueOf(darabok[2]));
lista.add(valtozas);
}
}
catch (Exception e) {
}
//3.FELADAT
System.out.println("3.Feladat: Változások száma: "+lista.size());
}
}
Here I want to convert the String to int, but I cant. I tried the Integer.Valueof(darabok[0]), but its not working. And nothing is happening, so the code is build, but quit from the while.
Based on the source code you have shown us, the problem is that there is a format mismatch between the input file and the program you are trying to read.
The program reads the file a line at a time, and splits it into fields using a single semicolon (with no whitespace!) as the file separator. Then it tries to parse the first three fields of each split line as integers.
For this to work the following must be true:
Every line must have at least three fields. (Otherwise you will get a ArrayIndexOutOfBound exception.)
The three fields must match the following regex: -?[0-9]+ i.e. an optional minus signed followed by one or more decimal digits.
The resulting number must be between Integer.MIN_VALUE and Integer.MAX_VALUE.
Elaborating on the above:
Leading and trailing whitespace characters are not allowed.
Embedded decimals markers and grouping characters are not allowed.
Scientific notation is not allowed.
Numbers that are too large or too small are not allowed.
Note that if any of the above constraints is not met, then the runtime system will throw an exception. Unfortunately, you surround your code with this:
try {
...
}
catch (Exception e) {
}
That basically ignores all exceptions by catching them and doing nothing in the handler block. You are saying to Java "if anything goes wrong, don't tell me about it!". So, naturally, Java doesn't tell you what is going wrong.
DON'T EVER DO THIS. This is called exception squashing, and it is a really bad idea1.
There are two ways to address this:
Print or log the stacktrace; e.g.
catch (Exception e) {
e.printStackTrace();
}
Remove the try / catch, and add throws IOException to the signature of your main method.
(You can't just remove the try / catch because new Scanner(fajl, "UTF8") throws IOException. That's a checked exception so must be handled or declared in the method signature.)
Once you have dealt with the exception properly you will get an exception message and stacktrace that tells you what is actually going wrong. Read it, understand it, and fix your program.
1 - It is like taping over the "annoying" red light that indicates that your car's oil level is low!

Is there difference if I call input.nextLine() as part of exception catching in every catch block or inside a final block at the end of try-catch?

For example, here I put it only once, but I know that I can put it several times. What is the difference?
try{
if(tasks.size() <= 0){
System.out.println("Nothing to remove, no tasks");
}
else{
System.out.println("Enter index of task to remove");
int index = input.nextInt();
input.nextLine();
tasks.remove(index);
}
}
catch(InputMismatchException ex){
System.out.println("Please enter only numbers");
}
catch(IndexOutOfBoundsException ex){
System.out.println("Invalid index number");
}
}
finally will be called always, regardless if you cough exception or not so yes, there is a difference.
Anyway assuming you are using Scanner you should avoid using try-catch as part of your logic (they should be used only if exceptional situations happen since creating exception may be expensive). Instead try to prevent throwing exceptions with little help of hasNextInt method.
So you can try with something like:
System.out.println("Enter index of task to remove");
while (!input.hasNextInt()){
System.out.println("That was not proper integer, please try again");
input.next();// to let Scanner move to analysing another value from user
// we need to consume that incorrect value. We can also use
// nextLine() if you want to consume entire line of
// incorrect values like "foo bar baz"
}
//here we are sure that inserted value was correct
int int index = input.nextInt();
input.nextLine();// move cursor after line separator so we can correctly read
// next lines (more info at http://stackoverflow.com/q/13102045/1393766)
The difference is clarity and simplicity.
The finally block will always execute, if present. Code which is common to the entire block can be located there. In the future if a different response is required it can be changed in a single location.
When common code is spread out in multiple locations you run the risk of changing some but not all instances which can result in unexpected failures.

Java Catch Exception - Empty String

I'm looking for an exception on how to catch an invalid String that is user input. I have the following code for a exception on an integer input:
try {
price = Integer.parseInt(priceField.getText());
}
catch (NumberFormatException exception) {
System.out.println("price error");
priceField.setText("");
break;
But I'm not aware of a specific exception for strings, the input is a simple JTextBox so the only incorrect input I can think of is if the user enters nothing into the box, which is what I'm looking to catch.
if (textField.getText().isEmpty())
is all you need.
Or maybe
if (textField.getText().trim().isEmpty())
if you also want to test for blank inputs, containing only white spaces/tabs.
You generally don't use exceptions to test values. Testing if a string represents an integer is an exception to the rule, because there is no available isInt() method in String.
You can do like
if (priceField.getText().isEmpty())
throw new Exception("priceField is not entered.");
You could check if priceField contains a string by using this:
JTextField priceField;
int price;
try {
// Check whether priceField.getText()'s length equals 0
if(priceField.getText().getLength()==0) {
throw new Exception();
}
// If not, check if it is a number and if so set price
price = Integer.parseInt(priceField.getText());
} catch(Exception e) {
// Either priceField's value's length equals 0 or
// priceField's value is not a number
// Output error, reset priceField and break the code
System.err.println("Price error, is the field a number and not empty?");
priceField.setText("");
break;
}
When the if-statement is true (If the length of priceField.getText() is 0) an exception gets thrown, which will trigger the catch-block, give an error, reset priceField and break the code.
If the if-statement is false though (If the length of priceField.getText() is greater or lower than 0) it will check if priceField.getText() is a number and if so it sets price to that value. If it not a number, a NumberFormatException gets thrown, which will trigger the catch-block etc.
Let me know if it works.
Happy coding :) -Charlie
if you want your exception to be thrown during the normal operation of the Java Virtual Machine, then you can use this
if (priceField.getText().isEmpty())
throw new RunTimeException("priceField is not entered.");

readUTF works once, then throws EOFException

I'm writing to a RandomAccessFile like that: (in a LinkedList's subclass)
file.setLength(0);
for (Person person : this)
file.writeUTF(person.getBlob());
Person.getBlob() returns a string of constant length, containing only basic alphanumeric characters, spaces and CRs (only one-byte characters). At this place the file contains exactly 100 records. (confirmed with a hex editor)
Then I try to read that file:
int counter = 0;
while (true) {
try {
add(Person.fromBlob(file.readUTF()));
} catch (EOFException e) {
System.out.println(counter + " records read from file.");
break;
} catch (Exception exception) {
throw new DBException(exception);
}
counter++;
}
I always end up with one record read correctly and an EOFException. What's wrong with this code?
I've found the solution. That class had a custom add() method that rewrote the file everytime something was added. At the beginning of the loop there were 100 entries, but after it executed once only one entry was left. There was also some extra code that had always added those missing 99 entries.
Replacing add() with super.add() solved the problem.

Java Try and catch

I have a java program that is supposed to handle an Exception, but the end result is far from what I intended it to be. Here is the overall idea of my program: it is supposed accept an input of zero and exit the program. The input dialog should cause an Exception which should be caught and print the message "bad number".
My brain is telling me I'm missing one line of code in the catch block.
here is my code:
import javax.swing.JOptionPane;
public class exceptTest {
public static void main(String[] args){
try {
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0"));
System.exit(0);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
You are not catching an exception here, you are simply making a if statement, you can just use an if/else.
try{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")){
System.exit(0);
}else{
JOptionPane.showMessageDialog(null, "bad number");
}
}catch (Exception ex){
ex.printStackTrace();
}
The catch you would only use for any exceptions showInputDialog() throws, but for your number check you are not catching anything, it just simply is not 0.
You don't execute your exception handling code because you never throw an exception. The code will execute the input, then test the input to be equal to "0", then based on that will or will not display a dialog, and then it will execute.
The throwing of an exception occurs either because something has happened outside the conditions that the code will handle, or because you throw one explicitly.
By "outside the conditions" etc., I mean something like dividing by 0. Java (nor any other language) will handle that, and an exception will be thrown. The normal steps of procedural processing will stop, and an execution handler will be called.
In your case, if you (for instance) attempted to parse the input to be a number, but the input was not a number, you would get an exception. This is different functionality than you say you wanted, but is a better illustration of what an exception is for. Something like
try
{
int numberEntered = Integer.parse(line);
JOptionPane.showMessageDialog(null, "Entered a number, parsed to " + numberEntered);
}
catch (NumberFormatException nfe)
{
JOptionPane.showMessageDialog(null, "Did not enter a number, but <" + line + ">");
}
shows the sort of thing exceptions are normally good for.
If you wanted to, you could define an exception, call it BadNumberException, and throw it in the code you have -- you would put it (I guess) in an else clause for your if statement. But your routine would be throwing the exception, and I think it is unusual for the routine that throws an exception to also catch it.
Hope that helps.
rc
You have a semi-colon after your if statement, it terminates the line and the compiler does not look for the rest of the if. Remove your semi-colon and it will work fine.
import javax.swing.JOptionPane;
public class exceptTest
{
public static void main(String[] args){
try
{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")) //semi-colon removed here
{
System.exit(0);
}
throw new IllegalArgumentException("Input was not 0");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
Your code does not throw an exception if the input is not equal to 0. Therefore, you never catch anything, thus no errormessage is shown on the screen.
You could do two things:
- throw an exception if the input is not 0 (then you will enter the catch)
or
- use an else with your if that displays the error message (then you don't need the try-catch for checking whether the input is 0)
Edit: And of course as Hunter McMillen noticed, you need to remove the semicolon after your if statement.

Categories

Resources