1. 程式人生 > >[Java in NetBeans] Lesson 16. Exceptions.

[Java in NetBeans] Lesson 16. Exceptions.

這個課程的參考視訊和圖片來自youtube

    主要學到的知識點有:

We want to handle the bad Error. (e.g bad input / bugs in program)

  • Error: a type of Exception  

    e.g   File I/O;   User Input, out of control.

 

 An example that handle the wrong input and out of range input. 

1. First we creat two java class (IntegerOutOfRangeException and InputMisMatchException)

 

public class IntegerOutOfRangeException extends Exception {
}
public class InputMisMatchException extends Exception {
}

 

2. Then we will use try and  catch to catch the exceptions. 

try {
    i = input.nextint();
    if (i < 1 || i > 10) {
        throw new integerOutOfRangeException();
    }
    catch (inputMisMatchException ex){
        System.out.println("you did not enter an integer.");
    }
    catch (integerOutOfRangeException ex){
        System.out.println("your input value is out of range.");
    }
}