Understanding try & catch and error handling

前端 未结 3 1392
我在风中等你
我在风中等你 2020-12-20 07:25
import java.util.Scanner;

public class Lab4_5 {
    public static void main(String[]args) {
        Scanner scan= new Scanner(System.in);

        int rows=0;
              


        
3条回答
  •  攒了一身酷
    2020-12-20 07:55

    You need to understand this please look into it.

    Basic understanding is

    try { 
       //Something that can throw an exception.
    } catch (Exception e) {
      // To do whatever when the exception is caught.
    } 
    

    There is also an finally block which will always be execute even if there is an error. it is used like this

    try { 
       //Something that can throw an exception.
    } catch (Exception e) {
      // To do whatever when the exception is caught & the returned.
    } finally {
      // This will always execute if there is an exception or no exception.
    }
    

    In your particular case you can have the following exceptions (link).

    InputMismatchException - if the next token does not match the Integer regular expression, or is out of range NoSuchElementException - if input is exhausted IllegalStateException - if this scanner is closed

    So you would need to catch exceptions like

    try { 
       rows=scan.nextInt();
    } catch (InputMismatchException e) {
      // When the InputMismatchException is caught.
      System.out.println("The next token does not match the Integer regular expression, or is out of range");
    } catch (NoSuchElementException e) {
      // When the NoSuchElementException is caught.
      System.out.println("Input is exhausted");
    } catch (IllegalStateException e) {
      // When the IllegalStateException is caught.
      System.out.println("Scanner is close");
    } 
    

提交回复
热议问题