서노썬
sun noes sun
서노썬
전체 방문자
오늘
어제
  • 카테고리 (142)
    • Java (89)
      • Day1 (20)
      • Day2 (16)
      • Day3 (4)
      • Day4 (5)
      • Day5 (2)
      • Day6 (2)
      • Day7 (4)
      • Day8 (6)
      • Day9 (3)
      • Day10 (0)
      • Day11 (0)
      • Day12 (0)
      • Day13 (3)
      • Day14 (0)
      • Day15 (0)
      • Day16 (0)
      • Day19 (0)
      • Day20 (0)
      • Day21 (2)
      • Day22 (4)
      • Day23 (2)
      • Day24 (5)
      • Day25 (4)
      • Day27 (2)
      • Day28 (3)
      • Day29 (1)
      • Day30 (1)
      • Day31 (0)
      • Day32 (0)
      • Dat33 (0)
      • Day34 (0)
      • Day35 (0)
      • Day36 (0)
    • HTML (37)
      • Day36 (20)
      • Day37 (3)
      • Day38 (2)
      • Day39 (8)
      • Day40 (3)
    • SQL (4)
      • Day40 (4)
      • Day41 (0)
      • Day42 (0)
      • Day43 (0)
      • Day44 (0)
      • Day45 (0)
    • JSP (0)
      • Day46 (0)
      • Day75 (0)
    • PYTHON (0)
      • Day75 (0)
      • Day76 (0)
    • Photo (12)

블로그 메뉴

  • 홈
  • 방명록

인기 글

최근 글

태그

  • java데이터타입
  • Java
  • 논리연산자
  • 자바연산자
  • 자바continue
  • 자바break
  • 자바자료형
  • java메뉴입력
  • 자바
  • java자료형

티스토리

hELLO · Designed By 정상우.
서노썬

sun noes sun

Java/Day22

[Java] 예외처리 문제

2021. 11. 28. 23:24

[ 예외처리 문제 ]

 

1. 다음 소스 코드는 컴파일시 에러가 난다. 이유는?

class ExceptionEx1 {
	public static void main(String[] args) 
	{
		try  {
			try	{	} catch (Exception e)	{ }
		} catch (Exception e)	{
			try	{	} catch (Exception e) { }	
		} // try-catch의 끝

		try  {

		} catch (Exception e)	{

		} // try-catch의 끝
	}	// main메서드의 끝

 

☞ catch 블럭 안에 또 try~catch문이 사용되었는데 위의 try에서와 참조변수의 이름이 중복 선언되었다.

 

 

2. 다음 소스코드는 예외가 발생하는 소스코드이다. 어디서 예외가 발생하나? 그리고 그 이유는?

class ExceptionEx2 {
	public static void main(String args[]) {
		int number = 100;
		int result = 0;

		for(int i=0; i < 10; i++) {
			result = number / (int)(Math.random() * 10);  // 제수가 0이 될 수 있어서 예외
			System.out.println(result);
		}
	} // main의 끝

 

☞ i의 값이 0일 때 0으로 나눗셈을 하게 되므로 예외상황이 발생하게 된다. (제수가 0이 될 수 있기 때문에)

 

 

3. 2번 소스 코드를 예외가 발생하지 않도록 수정해 보자.

class ExceptionEx3 {
	public static void main(String args[]) {
		int number = 100;
		int result = 0;

		for(int i=0; i < 10; i++) {
			try {
				result = number / (int)(Math.random() * 10);
				System.out.println(result);
			} catch (ArithmeticException e)	{
				System.out.println("0");	
			} // try-catch의 끝
		} // for의 끝
	} 
}

 

 

4. 다음 소스 코드의 실행 결과는?

class ExceptionEx4 {
	public static void main(String args[]) {
			System.out.println(1);			
			System.out.println(2);
			try {
				System.out.println(3);
				System.out.println(4);
			} catch (Exception e)	{
				System.out.println(5);
			} // try-catch의 끝
			System.out.println(6);
	}	// main메서드의 끝
}

 

☞ 예외상황이 발생하지 않으므로 5는 출력되지 않는다.
1
2
3
4
6

 

 

5. 다음 소스 코드의 실행 결과는?

class ExceptionEx5 {
	public static void main(String args[]) {
			System.out.println(1);			
			System.out.println(2);
			try {
				System.out.println(3);
				System.out.println(0/0);	
				System.out.println(4); 	
			} catch (ArithmeticException ae)	{
				System.out.println(5);
			}	// try-catch의 끝
			System.out.println(6);
	}	// main메서드의 끝
}

 

☞ System.out.println(0/0); 에서 에러상황이 발생하므로 try문을 빠져나가 catch문으로 가기 때문에 4는 출력되지 않는다.
1
2
3
5
6

 

 

6. 다음 소스 코드의 실행 결과는?

class ExceptionEx6 {
	public static void main(String args[]) {
		System.out.println(1);			
		System.out.println(2);
		try {
			System.out.println(3);
			System.out.println(0/0);
			System.out.println(4); 	
		} catch (Exception e)	{	// ArithmeticException대신 Exception을 사용.
			System.out.println(5);
		}	// try-catch의 끝
		System.out.println(6);
	}	// main메서드의 끝
}

 

☞ AtirhmeticException 클래스는 Exception클래스의 하위 클래스. ArithmeticException 대신 Exception이 사용되었다.
1
2
3
5
6

 

 

7. 다음 소스 코드의 실행 결과는?

class ExceptionEx7 {
	public static void main(String args[]) {
		System.out.println(1);			
		System.out.println(2);
		try {
			System.out.println(3);
			System.out.println(0/0);
			System.out.println(4); 		
		} catch (ArithmeticException ae)	{
			if (ae instanceof ArithmeticException) 
				System.out.println("true");	
			System.out.println("ArithmeticException");
		} catch (Exception e)	{
			System.out.println("Exception");
		}	// try-catch의 끝
		System.out.println(6);
	}	// main메서드의 끝
}

 

☞ 첫 번째 catch문에서 일치하는 내용을 찾았기 때문에 두 번째 catch문은 실행되지 않는다.
1
2
3
true
ArithmeticException
6

 

 

8. 다음 ExceptionEx10 클래스는 컴파일시 에러가 나고, ExceptionEx11은 런타임시에 예외가 발생한다.
그 이유는 무엇인가?

class ExceptionEx10 {
	public static void main(String[] args) {
		throw new Exception();		// Exception을 고의로 발생시킨다.
	}
} // checked 예외

class ExceptionEx11 {
	public static void main(String[] args) {
		throw new RuntimeException();	// RuntimeException을 고의로 발생시킨다.
	}
} // unchecked 예외

 

☞ ExceptionEx10 는 try~catch문 또는 throws를 사용하여 예외상황에 대한 선언을 필요로 한다. 하지만 RuntimeException의 경우 명시적으로 예외상황에 대한 체크를 필요로 하지 않기 때문에 try~catch문 또는 throws를 사용하여 선언해주지 않아도 되기 때문이다.

 

 

9. 다음 소스코드의 공통된 부분을 걷어내 보자.

class FinallyTest {
	public static void main(String args[]) {
		try {
			startInstall();		// 프로그램 설치에 필요한 준비를 한다.
			copyFiles();		// 파일들을 복사한다. 
			deleteTempFiles();	// 프로그램 설치에 사용된 임시파일들을 삭제한다.
		} catch (Exception e) {
			e.printStackTrace();
		    	deleteTempFiles();   // 프로그램 설치에 사용된 임시파일들을 삭제한다.
		} // try-catch의 끝
	} // main의 끝

   static void startInstall() { 
        /* 프로그램 설치에 필요한 준비를 하는 코드를 적는다.*/ 
   }
   static void copyFiles() { /* 파일들을 복사하는 코드를 적는다. */ }
   static void deleteTempFiles() { /* 임시파일들을 삭제하는 코드를 적는다.*/ }
}

/*
startInstall(), copyFiles(), deleteTempFiles()에 주석문 이외에는 아무런 문장이 없지만, 각 메서드의 의미에 해당하는 작업을 수행하는 코드들이 작성되어 있다고 가정하자.
*/

 

☞ 결과

class FinallyTest2 {
	public static void main(String args[]) {
		try {
			startInstall();		// 프로그램 설치에 필요한 준비를 한다.
			copyFiles();		// 파일들을 복사한다. 
		} catch (Exception e)	{
			e.printStackTrace();
		} finally {
			deleteTempFiles();	// 프로그램 설치에 사용된 임시파일들을 삭제한다.
		} // try-catch의 끝
	}	// main의 끝

   static void startInstall() {
        /* 프로그램 설치에 필요한 준비를 하는 코드를 적는다.*/ 
   }
   static void copyFiles() { /* 파일들을 복사하는 코드를 적는다. */ }
   static void deleteTempFiles() { /* 임시파일들을 삭제하는 코드를 적는다.*/}
}

 

 

10. 다음 소스코드의 실행 결과를 적어보자.

class FinallyTest3 {
	public static void main(String args[]) {
		// method1()은 static메서드이므로 인스턴스 생성없이 직접 호출이 가능하다.
		FinallyTest3.method1();		
		System.out.println("method1()의 수행을 마치고 main메서드로 돌아왔습니다.");
	}	// main메서드의 끝

	static void method1() {
		try {
			System.out.println("method1()이 호출되었습니다.");
			return;		// 현재 실행 중인 메서드를 종료한다.
		}	catch (Exception e)	{
			e.printStackTrace();
		} finally {
			System.out.println("method1()의 finally블럭이 실행되었습니다.");
		}
	}	// method1메서드의 끝
}

 

☞

method1()이 호출되었습니다.
method1()의 fianlly블럭이 실행되었습니다.
method1()의 수행을 마치고 main메서드로 돌아왔습니다.

 

'Java > Day22' 카테고리의 다른 글

[Java] MenuException  (0) 2021.11.28
[Java] 단계별 프로젝트 - 전화번호 관리 프로그램 06단계  (0) 2021.11.28
[Java] 예외처리 설명  (0) 2021.11.28
    'Java/Day22' 카테고리의 다른 글
    • [Java] MenuException
    • [Java] 단계별 프로젝트 - 전화번호 관리 프로그램 06단계
    • [Java] 예외처리 설명

    티스토리툴바