~홍~

Java _ Exception 15 본문

java/학원수업

Java _ Exception 15

~홍~ 2020. 12. 6. 20:55
728x90

Exception 01 

=> 컴파일 에러 

// 컴파일 에러 : 소스코드 빌드 시 발생하는 에러
// -> 실행 파일이 만들어지지 않기 때문에 실행할 수 없음
// 예외(Exception) :
// -> 소스코드를 빌드할 때는 에러가 없었지만,
//   실행파일을 실행할 때 발생하는 오류
// 논리적 오류 :
// -> 컴파일 에러도 없고, 실행할 때 예외도 발생하지 않지만
//   논리적인 문제 때문에 원하는 실행 결과가 나오지 않는 경우

public class ExMain01 {

	public static void main(String[] args) {
//		int 123; // 컴파일 에러
		
//		int n = 123 / 0; // 예외 발생 
		
		int result = findMax(20, 1);
		System.out.println("result = " + result);
		
	} // end main()
	
	public static int findMax(int x, int y) {
		return (x < y) ? x : y;
	}

} // end ExMain01

출력 

더보기

result = 1


Exception 02

 

public class ExMain02 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
	
		int n1 = sc.nextInt();
		int n2 = sc.nextInt();
		sc.close();
		
//		if (n2 != 0) {
//			int result = n1 / n2;
//			System.out.println("result = " + result);			
//		} else {
//			System.out.println("0이 아닌 값을 입력하세요");
//		}
		
		// 예외 처리 : try 구문
		// try {
		//		정상적인 실행 문장들;
		// } catch (예외클래스 변수이름) {
		// 		예외상황일 때 실행할 문장들
		// }
		System.out.println();
		
		try {
			System.out.println("try 내부");
			int result = n1 / n2;
			System.out.println("result = " + result);
		} catch (Exception e) {
			System.out.println("예외 발생!");
		}
		
		System.out.println("프로그램 종료");
		
	} // end main()

} // ExMain02

Exception 03

 

public class ExMain03 {

	public static void main(String[] args) {
		try {
			System.out.println("try 내부");
			int[] array = new int[10];
			array[13] = 100;
			System.out.println(array[10]);
		} catch (Exception e) {
			System.out.println("예외 메시지 : " + e.toString());
		}
		
		System.out.println("프로그램 종료");
	} // end main()

} // end ExMain03

출력

더보기

try 내부
예외 메시지 : java.lang.ArrayIndexOutOfBoundsException: : Index 13 out of bounds for length 10

프로그램 종료


Exception 04

 

public class ExMain04 {

	public static void main(String[] args) {
		try {
			System.out.println("try 내부");
			String name = null;
			System.out.println("문자열 길이 : " + name.length());
		} catch (NullPointerException e) {
			System.out.println("예외 메시지 : " + e.getMessage());
		}
		System.out.println("프로그램 종료");
		
	} // end main()

} // end ExMain04

츨력 

더보기

try 내부
예외 메시지 : Cannot invoke "String.length()" because "name" is null

프로그램 종료


Exception 05

 

public class ExMain05 {

	public static void main(String[] args) {
		// 하나의 try 구문에서 여러 개의 catch를 사용하는 방법1
		try {
			int x = 12345;
			int y = 1;
			int result = x / y;
			System.out.println("result = " + result);
			
			int[] array = new int[10];
			array[11] = 10;
			System.out.println("array[11] = " + array[11]);
			
			String name = null;
			System.out.println("문자열 길이 : " + name.length());
		} catch(ArithmeticException e) {
			System.out.println("산술연산 예외 : " + e.getMessage());
		} catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("배열 인덱스 예외 : " + e.getMessage());
		} catch (Exception e) {
			System.out.println("예외 : " + e.getMessage());
		}
		
		// 하나의 try 구문에서 여러 개의 catch를 사용하는 경우,
		// 자식 클래스의 Exception을 먼저 catch 구문에서 사용하고,
		// 가장 마지막에 최상위 부모 클래스인 Exception을 사용해야 함
		
		System.out.println("프로그램 종료");
	} // end main()

} // end ExMain05

출력 

더보기

result = 12345
배열 인덱스 예외 : Index 11 out of bounds for length 10
프로그램 종료


Exception 06

 

public class ExMain06 {

	public static void main(String[] args) {
		// 하나의 try 구문에서 여러 개의 catch를 사용하는 방법2 : Java 7버전부터
		// try {
		// 		정상 상황일 때 실행할 코드;
		// } catch (Ex1 | Ex2 | Ex3 ... e) {
		//		예외 상황일 때 실행할 코드;
		// } catch (Exception e) { ... }
		// 예외(Exception)의 종류들을 나열할 때는 부모 예외 클래스가 포함되면 안됨
		// 최상위 예의 클래스(Exception)은 항상 마지막에 catch 구문에서만 사용
		
		try {
			System.out.println("try 시작");
			int result = 123 / 10;
			int[] array = new int[10];
			array[10] = 10;
			System.out.println("try 끝");
		} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
			System.out.println("예외 : " + e.getMessage());
		} catch (Exception e) {
			System.out.println("예외 : " + e.getMessage());
		}
	} // end main()

} // end ExMain06

출력  

더보기

try 시작
예외 : Index 10 out of bounds for length 10


Exception 07

 

public class ExMain07 {

	public static void main(String[] args) {
		// try {
		// 		정상적인 경우에 실행할 코드들;
		// } catch (Exception e) {
		// 		예외 상황일 때 실행할 코드;
		// } finally {
		//		정상적인 경우든, 예외 상황이든 상관없이 항상 실행할 코드
		// }
		// (주의) try 블록이나 catch 블록 안에 return; 이 있더라도
		// return 보다 먼저 finally 블록이 실행되고, 그 후에 return이 실행됨!
		
		Scanner sc = new Scanner(System.in);
		try {
			System.out.println("try 시작");
			int a = sc.nextInt();
			int b = sc.nextInt();
			int result = a / b;
			System.out.println("try 끝 : result = " + result);
		} catch(Exception e) {
			System.out.println("예외 : " + e.getMessage());
		} finally {
			System.out.println("finally : 언제 실행될까요?");
			sc.close();
		}
		
		System.out.println("프로그램 종료");
		
		
	} // end main()

} // end ExMain07

Exception 08

public class ExMain08 {

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

		while(true) {
			try {
				System.out.println("메뉴 선택>");
				int choice = Integer.parseInt(sc.nextLine());
				System.out.println("choice : " + choice);
				break;
			} catch(NumberFormatException e) {
				System.out.println("숫자가 아닙니다. ");
			}
		}
		
		sc.close();
	} // end main()

} // end ExMain08

Exception 09

=> 사용자 정의 예외(Exception) 클래스를 만드는 방법

// 사용자 정의 예외(Exception) 클래스를 만드는 방법
class ScoreInputException extends Exception {
	public ScoreInputException(String msg) {
		super(msg);
	}
} // end ScoreInputException

class AgeInputException extends Exception {
	public AgeInputException(String msg) {
		super(msg);
	}
} // end AgeInputException

Main 

public class ExMain09 {
	private static Scanner sc = new Scanner(System.in);
	
	public static void main(String[] args) {
		int korean;
		try {
			korean = inputScore();
			System.out.println("국어 점수 : " + korean);
		} catch (ScoreInputException e) {
			System.out.println("예외 : " + e.getMessage());
		}
	} // end main()
	
	private static int inputScore() throws ScoreInputException {
		System.out.println("점수 입력>");
		int score = sc.nextInt();
		// 1. 입력받은 점수가 0 ~ 100 사이가 아니면
		// 예외(Exception)을 생성해서 던짐(throws)
		if (score < 0 || score > 100) {
			ScoreInputException ex = new ScoreInputException("점수 입력 오류 : " + score);
			throw ex;
		}
		return score;
	}

} // end ExMain09

'java > 학원수업' 카테고리의 다른 글

Java _ File 17  (0) 2020.12.07
Java _ Thread 16  (0) 2020.12.06
Java _ Lambda 14  (0) 2020.12.06
Java _ InnerClass 13  (0) 2020.12.06
Java _ Collection 12  (0) 2020.12.06
Comments