이것은 코드 샘플입니다. 5 분모 : 나는 분자 입력했다면 0Why/inputMismatchException을 추가 할시기는 언제입니까?
이 같은 예외가 얻을 : 내가 포함 알고
Exception in thread "main" java.lang.ArithmeticException:/by zero
at ExceptionHandling.DivideByZeroExceptions.quotient(DivideByZeroExceptions.java:10)
at ExceptionHandling.DivideByZeroExceptions.main(DivideByZeroExceptions.java:22)
을 (산술 예외를 throw) 그러나 나는 것을 어떻게 알 것 inputMismatchException을 사용해야합니까?
// Try DivideByZeroExceptions
public class DivideByZeroExceptions {
public static int quotient(int numerator, int denominator) {
return numerator/denominator;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer numerator: ");
int numerator = input.nextInt();
System.out.println("Please enter an integer denominator: ");
int denominator = input.nextInt();
int result = quotient(numerator, denominator);
System.out.printf("\nResult: %d/%d = %d\n", numerator, denominator,
result);
}
}
이 경우 예외가 발생하지 않을 것이므로 입력을 확인하고 사용자에게 친숙한 오류 메시지와 다시 시도 할 수있는 기회를 제공합니다. 예외는 사용자에게 친숙하지 않습니다. –
그래서 언제 예외를 사용해야합니까? 예외를 사용하는 것이 더 낫다는 예제를주세요. – AppSensei
메서드 나 라이브러리를 호출하는 소프트웨어가 예외를 잡을 것으로 예상되면 Exception을 throw해야합니다. –