English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
예외는 프로그램이 실행 중에 발생하는 문제(실행 중 오류)입니다. 예외가 발생하면 프로그램이 갑자기 중지되고, 예외가 발생한 행 이후의 코드는 절대로 실행되지 않습니다.
import java.util.Scanner; public class ExceptionExample { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter first number:"); int a = sc.nextInt(); System.out.println("Enter second number:"); int b = sc.nextInt(); int c = a/b; System.out.println("The result is: ");+c); } }
출력 결과
첫 번째 숫자를 입력하세요: 100 두 번째 숫자를 입력하세요: 0 main 스레드에서 예외 발생 java.lang.ArithmeticException: / by zero at ExceptionExample.main(ExceptionExample.java:10)
여러 개의 try 블록과 단일 catch 블록을 함께 사용할 수 없습니다. 각 try 블록은 catch 또는 마지막에 바로 이어져야 합니다. 하지만, 여러 개의 try 블록에 대해 단일 catch 블록을 사용하려고 시도하면 컴파일 시 에러가 발생합니다.
다음 Java 프로그램은 여러 개의 try 블록에 대해 단일 catch 블록을 사용하려고 시도합니다.
class ExceptionExample{ public static void main(String args[]) { int a,b; try { a=Integer.parseInt(args[0]); b=Integer.parseInt(args[1]); } try { int c=a/b; System.out.println(c); }catch(Exception ex) { System.out.println("Please pass the args while running the program"); } } }
ExceptionExample.java:4: 에러: 'try' 없이 'catch', 'finally' 또는 리소스 선언 try { ^ 1 에러