Home > Net >  Handling Errors with try and catch blocks
Handling Errors with try and catch blocks

Time:09-17

I Have a question abouth the code for handling erros made by the user.

So the thing is, I need my user to add a name of a program, to add the memory that program takes in the RAM and to add the time he will have that program open.

I need to add in my code defensive programming, so I thought maybe I could do it by checking if the user actually add the type of the variables that the program need, or if it didn't.

Either way I am confused on how to use the try and catch blocks, for now this is what I have...

        System.out.println("add program Id");
        String programID = scan.next();
        try{
            String check;
            check  = programID;
        }catch(Exception e){
            System.out.println("add a value of String type");
        }

CodePudding user response:

That doesn't work.

anything you can type is a string. I can type '5'. That's a string. You may think it is a number, but this entire block of text is a String, and '5' is in it.

No text is a string too. String x = ""; compiles fine.

Thus, no exception would ever occur here, and it's not clear what scenario you are trying to detect.

Perhaps a programID is of the form: "one capital letter (and only english capitals, not Ü for example), and then up to 3 different digits". For example, 'Z5' or 'Y495'.

You'd need to write code to detect this, no need for try/catch. For example, regular expressions:

private static final Pattern PROGRAM_ID_PATTERN = Pattern.compile("^[A-Z]\\d{1,3}$");

public static void main(String[] args) {
  ....
  String programId;
  do {
    programId = scanner.next();
    if (!PROGRAM_ID_PATTERN.matcher(programId).matches()) {
      System.err.println("Enter a valid program ID, e.g. A123");
    } else {
      break;
    }
  } while (true);
}

Exceptions are for when a method has multiple different ways to exit.

For example, imagine this method:

byte[] contentsOfFile = Files.readFileFully("myfile.txt");

The readFileFully method seems simple: You provide the name of a file, and it returns a byte array with its contents.

However, that's just one way that could go. What if the file doesn't exist? What if the file exists, but your process doesn't have read access rights? What if the disk is failing or it's a removable drive and it's yanked out halfway through reading it?

These somewhat predictable potential alternate ways out are generally done by exceptions. That method would be throwing FileNotFoundException, noReadAccessException, and more generally IOException, for example.

There's no 'that is not a string' variant of scanner.next().

There is scanner.next(Pattern) which you could use:

private static final Pattern PROGRAM_ID_PATTERN = Pattern.compile("^[A-Z]\\d{1,3}$");

public static void main(String[] args) {
  ....
  String programId;
  do {
    try {
      programId = scanner.next(PROGRAM_ID_PATTERN);
      break;
    } catch (NoSuchElementException e) {
      System.err.println("Enter a valid program ID, e.g. A123");
    }
  } while (true);
}

The javadoc generally explains what exceptions can occur; if a method doesn't mention any, you're not supposed to try/catch there.

  • Related