#예외사항
- if문은 예외 처리 이외의 용도로도 사용되기 때문에,
프로그램 코드 상에서 예외처리 부분을 구분하기가 쉽지 않다.
# try catch문 : 던지고 받는 것!
- try : 예외가 발생할만한 영역을 감싸는 용도
catch : 발생한 예외의 처리를 위한 코드를 묶어두는 용도
ex)
try
{
// try 영역
}
catch(AAA e) // catch는 해당 영역만 처리하는 것!
{
// catch 영역
}
- if와 else처럼 try와 catch 사이에는 아무 것도 들어갈 수 없다!
try 영역에서 발생한 AAA에 해당하는 예외상황은 이어서 등장하는 catch 영역에서 처리된다.
- catch 영역에서 모든 예외상황을 처리하는 것은 아니다.
매개변수 선언이 있는데(AAA e), 이 부분에 명시되어 있는 유형의 예외상황만 처리가 가능하다.
ex)
import java.util.Scanner;
class DivideByZero
{
public static void main(String[] args)
{
System.out.print("두 개의 정수 입력: ");
Scanner keyboard=new Scanner(System.in);
int num1=keyboard.nextInt();
int num2=keyboard.nextInt();
try
{
System.out.println("나눗셈 결과의 몫: "+(num1/num2));
System.out.println("나눗셈 결과의 나머지: "+(num1%num2));
}
catch(ArithmeticException e)
{
System.out.println("나눗셈 불가능"); // 예외를 처리하는 것
System.out.println(e.getMessage());
}
System.out.println("프로그램을 종료합니다.");
}
}
ex)
class RuntimeExceptionCase
{
public static void main(String[] args)
{
try
{
int[] arr=new int[3];
arr[-1]=20; // 배열은 0부터 시작하여 불가능하다
// new ArrayIndexOutOfBoundsException()을 생성 후 던진다!
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage()); // 어떤 것에 대한 에러인지 출력
}
try
{
Object obj=new int[10];
String str=(String)obj; //int형 배열이 String으로 형변환 되지 않기 때문에 에러발생
}
catch(ClassCastException e)
{
System.out.println(e.getMessage());
}
try
{
int[] arr=new int[-10]; // 배열의 크기를 음수로 지정할 수 없어 에러발생
}
catch(NegativeArraySizeException e)
{
System.out.println(e.getMessage());
}
try
{
String str=null;
int len=str.length(); // null point reception 에러발생
}
catch(NullPointerException e)
{
System.out.println(e.getMessage());
}
}
}
ex)
import java.util.Scanner;
class ExceptionHandleUseIf
{
public static void main(String[] args)
{
Scanner keyboard=new Scanner(System.in);
int[] arr=new int[100];
for(int i=0; i<3; i++)
{
System.out.print("피제수 입력: ");
int num1=keyboard.nextInt();
System.out.print("제수 입력: ");
int num2=keyboard.nextInt();
if(num2==0)
{
System.out.println("제수는 0이 될 수 없습니다.");
i-=1;
continue;
}
System.out.print("연산결과를 저장할 배열의 인덱스 입력: ");
int idx=keyboard.nextInt();
if(idx<0 || idx>99)
{
System.out.println("유효하지 않은 인덱스 값입니다.");
i-=1;
continue;
}
arr[idx]=num1/num2;
System.out.println("나눗셈 결과는 "+arr[idx]);
System.out.println("저장된 위치의 인덱스는 "+idx);
}
}
}
ex) 위의 예제 변형
import java.util.Scanner;
class ExceptionHandleUseTryCatch
{
public static void main(String[] args)
{
Scanner keyboard=new Scanner(System.in);
int[] arr=new int[100];
for(int i=0; i<3; i++)
{
try
{
System.out.print("피제수 입력: ");
int num1=keyboard.nextInt();
System.out.print("제수 입력: ");
int num2=keyboard.nextInt();
System.out.print("연산결과를 저장할 배열의 인덱스 입력: ");
int idx=keyboard.nextInt();
arr[idx]=num1/num2;
System.out.println("나눗셈 결과는 "+arr[idx]);
System.out.println("저장된 위치의 인덱스는 "+idx);
}
catch(ArithmeticException e)
{
System.out.println("제수는 0이 될 수 없습니다.");
i-=1;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("유효하지 않은 인덱스 값입니다.");
i-=1;
continue;
}
}
}
}
- finally : try 구문에서 예외상황의 발생여부와 상관없이 항상 실행된다.
ex)
class FinallyTest
{
public static void main(String[] args)
{
boolean divOK=divider(4, 2);
if(divOK)
System.out.println("연산 성공");
else
System.out.println("연산 실패");
divOK=divider(4, 0);
if(divOK)
System.out.println("연산 성공");
else
System.out.println("연산 실패");
}
public static boolean divider(int num1, int num2)
{
try
{
int result=num1/num2;
System.out.println("나눗셈 결과는 "+result);
return true;
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
return false;
}
finally //finally 구문은 try 구문에 들어가면 무조건 실행되는 영역이다!
{
System.out.println("finally 영역 실행");
}
}
}
- 예외를 처리하기 위한 클래스 중 최상위 클래스는 Throwable class이다.
# Error 클래스는 프로그램의 실행을 멈춰야 할 정도의 매우 심각한 오류상황을 표현하는데 사용이 된다.
Error를 상속하는 클래스의 오류상황이 발생하면, 그냥 프로그램이 종료되도록 놔두는 것이 상책이다.
(프로그램이 종료된 뒤 소스코드를 수정하는 등의 방식으로 원인을 해결해야 한다.)
- Error -> VirtualMachineError
-> OutOfMemoryError (상속 받는 순서)
ㄴ 메모리 공간 부족 표현 예외 클래스 : 메모리가 효율적으로 사용되도록 소스코드 자체를 변경해야 함
# 그래서 Throwable클래스의 하위 클래스 중 Exception 클래스로 상속받는 것!
이는 예외 클래스가 되어서 try~catch 예외처리 메커니즘에 활용이 가능한 클래스가 된다.
- getMessage는 Throwable 클래스가 가지고 있는 메소드이다.
따라서 하위 클래스인 Exception 클래스도 getMessage를 가지고 있다.
Exception 클래스의 생성자 호출을 통해서 전달된 문자열이 (getMessage)의 호출을 통해서 반환된다.
★ Exception을 상속하는 클래스의 예외 상황이 임의의 메소드 내에서 발생 가능하다면,
해당 메소드는 반드시 다음 두 가지 중 한가지 방법을 선택해서 정의되어야 한다.
① try~catch문을 이용해서 메소드 내에서 예외를 처리하도록 정의한다.
② throws를 이용해서 메소드를 호출한 영역으로 예외가 전달되도록 정의한다.
# throw : 받지 않고 던진다는 의미
예외상황이 발생되었음을 자바 가상머신에게 알리는 키워드
이 문장이 실행되면서 자바의 예외처리 메커니즘이 동작하게 된다.
# RuntimeException : Exception의 하위클래스이나 성격이 Error클래스와 비슷하다.
Exception을 상속하는 다른 예외 클래스들과의 차이점이다.
하여 위의 두 가지 방법을 필요로 하지 않는다.
- RuntimeException의 하위 클래스
ArrayIndexOutOfBoundsException // 배열의 인덱스 범위를 벗어났을 때
ClassCastException // 형변환 오류 시
NegativeArraySizeException // 배열의 크기를 음수로 지정했을 때
NullPointerException
예외의 성격이 보여주듯이 특별한 경우가 아니면,
이들에 대해서는 try~catch문을 이용해서 예외처리를 하지 않는다.
- Error와 RuntimeException 클래스의 차이점
RuntimeException은 Error를 상속하는 예외 클래스처럼 치명적인 상황을 표현하지 않는다.
따라서 예외발생 이후에도 프로그램의 실행을 이어가기 위해 try~catch문으로 해당 예외를 처리하기도 한다.
ex)
import java.util.Scanner;
class AgeInputException extends Exception
{
public AgeInputException()
{
super("유효하지 않은 나이가 입력되었습니다.");
//Exception은 Throwable클래스 상속 받았으므로 getMessage 메소드가 안에 있다
}
}
class ProgrammerDefineException
{
public static void main(String[] args)
{
System.out.print("나이를 입력하세요: ");
try // 예외 발생 가능성 있는 부분
{
int age=readAge();
System.out.println("당신은 "+age+"세입니다.");
}
catch(AgeInputException e)
{
System.out.println(e.getMessage());
}
}
public static int readAge() throws AgeInputException // try catch가 없어서 던지겠다고 표시한 것
{
Scanner keyboard=new Scanner(System.in);
int age=keyboard.nextInt();
if(age<0) // 개발자가 예외로 생각하여 규정한 것
{
AgeInputException excpt=new AgeInputException();
// 사용자 정의 예외 클래스는 자바컴파일러에게 예외발생했다는 것을 알려주려 생성함
throw excpt;
// 생성한 객체를 던지게 되면 예외발생했다는 것을 자바버츄얼머신이 인지한다
// 에러를 던지면 받거나, 받지 않을거라고 메소드에 던져짐을 명시해야 함
}
return age;
}
}
ex)
import java.util.Scanner;
class AgeInputException extends Exception
{
public AgeInputException()
{
super("유효하지 않은 나이가 입력되었습니다.");
}
}
class ThrowsFromMain
{
public static void main(String[] args) throws AgeInputException
// 적어도 메인메소드에서 던짐 표시해야 함(메인 메소드에서 던지면 아예 버리겠다는 의미로 자주 사용하는 것은 좋지 않다)
{
System.out.print("나이를 입력하세요: ");
int age=readAge();
System.out.println("당신은 "+age+"세입니다.");
}
public static int readAge() throws AgeInputException
{
Scanner keyboard=new Scanner(System.in);
int age=keyboard.nextInt();
if(age<0)
{
AgeInputException excpt=new AgeInputException();
throw excpt;
}
return age;
}
}
// Tip. 같은 프로젝트 내에는 같은 이름의 클래스가 있으면 에러 발생한다.
- printStackTrace : 예외가 발생된 곳을 순차적으로 보여주는 메소드, Throwable 클래스에 속해 있다.
호출한 곳부터 역순으로 보여준다!
ex)
import java.util.Scanner;
class AgeInputException extends Exception
{
public AgeInputException()
{
super("유효하지 않은 나이가 입력되었습니다.");
}
}
class NameLengthException extends Exception
{
String wrongName;
public NameLengthException(String name)
{
super("잘못된 이름이 삽입되었습니다.");
wrongName=name;
}
public void showWrongName()
{
System.out.println("잘못 입력된 이름: "+ wrongName);
}
}
class PersonalInfo
{
String name;
int age;
public PersonalInfo(String name, int age)
{
this.name=name;
this.age=age;
}
public void showPersonalInfo()
{
System.out.println("이름: "+name);
System.out.println("나이: "+age);
}
}
class PrintStackTrace
{
public static Scanner keyboard=new Scanner(System.in);
public static void main(String[] args)
{
try
{
PersonalInfo readInfo=readPersonalInfo();
readInfo.showPersonalInfo();
}
catch(AgeInputException e)
{
e.printStackTrace();
}
catch(NameLengthException e) // 잡는 곳!
{
e.showWrongName();
e.printStackTrace(); // 에러가 발생된 곳을 순차적으로 출력해서 보여주는 것
}
}
public static PersonalInfo readPersonalInfo()
throws AgeInputException, NameLengthException // 여러 개 가능, 던짐 명시
{
String name=readName();
int age=readAge();
PersonalInfo pInfo=new PersonalInfo(name, age);
return pInfo;
}
public static String readName() throws NameLengthException
{ // ㄴ 던져짐을 명시하는 것
System.out.print("이름 입력: ");
String name=keyboard.nextLine();
if(name.length()<2) // 이름은 2글자 이상이기 때문에!
throw new NameLengthException(name);
return name;
}
public static int readAge() throws AgeInputException
{
System.out.print("나이 입력: ");
int age=keyboard.nextInt();
if(age<0)
throw new AgeInputException();
return age;
}
}
- Object 클래스의 Clone이라는 메소드를 호출해서 쓰려고 한다.
clone는 상황에 따라서 CloneNotSupportedException 이라는 예외를 전달하는 메소드이다.(API 참조)
ㄴ 예외 처리 해줘야 한다
ex) 에러 발생 예시
public void simpleMethod(int n) //컴파일 에러 발생 예시
{
MyClass my = new MyClass();
my.clone(); // Object에 있는 것
...
}
ex) 에러 수정 예시
public void simpleMethod(int n)
{
MyClass my = new MyClass();
try
{
my.clone();
}
catch(CloneNotSupportedException e) { ... }
...
}
public void simpleMethod(int n) throws CloneNotSupportedException
{
MyClass my = new MyClass();
my.clone();
........
}
- 자바버추얼머신의 예외처리방식
가상머신의 예외처리1 getMessage 메소드를 호출한다.
가상머신의 예외처리2 예외상황이 발생해서 전달되는 과정을 출력해준다. (PrintStackTrace)
가상머신의 예외처리3 프로그램을 종료한다.
Q.
1. 제수(나누는 수)가 0이 되었을 때 예외 처리하는 소스를 만드시오.
A.
import java.util.Scanner;
class DivideByZero
{
public static void main(String[] args)
{
System.out.print("두 개의 정수 입력: ");
Scanner keyboard=new Scanner(System.in);
int num1=keyboard.nextInt();
int num2=keyboard.nextInt();
try
{
System.out.println("나눗셈 결과의 몫: "+(num1/num2));
System.out.println("나눗셈 결과의 나머지: "+(num1%num2));
}
catch(ArithmeticException e)
{
System.out.println("나눗셈 불가능");
System.out.println(e.getMessage());
}
System.out.println("프로그램을 종료합니다.");
}
}
2. ( )는 예외상황을 알리기 위해서 정의된(또는 앞으로 여러분이 정의할),
모든 예외 클래스들이 상속하는 ( ) 클래스에 정의되어 있는 메소드이다.
모든 예외 클래스들이 ( ) 클래스를 상속.
A.
( getMessage )는 예외상황을 알리기 위해서 정의된(또는 앞으로 여러분이 정의할),
모든 예외 클래스들이 상속하는 ( Throwable ) 클래스에 정의되어 있는 메소드이다.
모든 예외 클래스들이 ( Throwable ) 클래스를 상속.
3. 예외 상황을 알리는 클래스
- 배열의 접근에 잘못된 인덱스 값을 사용하는 예외상황
- 허용할 수 없는 형변환 연산을 진행하는 예외상황
- 배열선언 과정에서 배열의 크기를 음수로 지정하는 예외상황
- 참조변수가 null로 초기화 된 상황에서 메소드를 호출하는 예외상황
A.
- ArrayIndexOutOfBoundsException
- ClassCastException
- NegativeArraySizeException
- NullPointerException
4. 3번에 있는 예외상황을 알리는 클래스를 이용하여 소스코드를 작성해 보시오.
A.
class RuntimeExceptionCase
{
public static void main(String[] args)
{
try
{
int[] arr=new int[3];
arr[-1]=20;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
try
{
Object obj=new int[10];
String str=(String)obj;
}
catch(ClassCastException e)
{
System.out.println(e.getMessage());
}
try
{
int[] arr=new int[-10];
}
catch(NegativeArraySizeException e)
{
System.out.println(e.getMessage());
}
try
{
String str=null;
int len=str.length();
}
catch(NullPointerException e)
{
System.out.println(e.getMessage());
}
}
}
5. 문제5의 소스코드는 if문을 이용한 예외처리 부분이 코드의 중간중간에 삽입되어 있다.
따라서 코드를 분석하는데 있어서 불편함이 따를 수 있다.
그러나 try~catch문을 활용하면 예외처리를 위한 코드를 완전히 별도로 묶을 수 있다.
하나의 try 영역에 둘 이상의 catch 영역을 구성할 수 있기 때문이다.
문제에 있는 소스코드를 try~catch문으로 변경해 보자.
import java.util.Scanner;
class ExceptionHandleUseIf
{
public static void main(String[] args)
{
Scanner keyboard=new Scanner(System.in);
int[] arr=new int[100];
for(int i=0; i<3; i++)
{
System.out.print("피제수 입력: ");
int num1=keyboard.nextInt();
System.out.print("제수 입력: ");
int num2=keyboard.nextInt();
if(num2==0)
{
System.out.println("제수는 0이 될 수 없습니다.");
i-=1;
continue;
}
System.out.print("연산결과를 저장할 배열의 인덱스 입력: ");
int idx=keyboard.nextInt();
if(idx<0 || idx>99)
{
System.out.println("유효하지 않은 인덱스 값입니다.");
i-=1;
continue;
}
arr[idx]=num1/num2;
System.out.println("나눗셈 결과는 "+arr[idx]);
System.out.println("저장된 위치의 인덱스는 "+idx);
}
}
}
A.
import java.util.Scanner;
class ExceptionHandleUseTryCatch
{
public static void main(String[] args)
{
Scanner keyboard=new Scanner(System.in);
int[] arr=new int[100];
for(int i=0; i<3; i++)
{
try
{
System.out.print("피제수 입력: ");
int num1=keyboard.nextInt();
System.out.print("제수 입력: ");
int num2=keyboard.nextInt();
System.out.print("연산결과를 저장할 배열의 인덱스 입력: ");
int idx=keyboard.nextInt();
arr[idx]=num1/num2;
System.out.println("나눗셈 결과는 "+arr[idx]);
System.out.println("저장된 위치의 인덱스는 "+idx);
}
catch(ArithmeticException e)
{
System.out.println("제수는 0이 될 수 없습니다.");
i-=1;
continue;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("유효하지 않은 인덱스 값입니다.");
i-=1;
continue;
}
}
}
}
6. 다음은 컴파일에러가 발생하는 소스코드이다. 무엇이 문제인가?
try
{
...
}
catch(Throwable e) // 모든 예외를 다 처리하기 때문에!
{
...
}
catch(ArithmeticException e)
{
...
}
A.
모든 예외 클래스를 상속하는 최상위 클래스인 Throwable이 앞에 있어 에러가 발생한다.
ArithmeticException과 위치를 바꾸거나 ArithmeticException 부분을 삭제해주면 컴파일에러가 해결된다.
try
{
...
}
catch(ArithmeticException e)
{
...
}
catch(Throwable e)
{
...
}
7. 예외 상황의 발생여부와 상관없이 항상 실행되는 영역에 쓰는 키워드는 무엇이고,
그것을 이용하여 소스코드를 작성해 보시오.
A. finally
class FinallyTest
{
public static void main(String[] args)
{
boolean divOK=divider(4, 2);
if(divOK)
System.out.println("연산 성공");
else
System.out.println("연산 실패");
divOK=divider(4, 0);
if(divOK)
System.out.println("연산 성공");
else
System.out.println("연산 실패");
}
public static boolean divider(int num1, int num2)
{
try
{
int result=num1/num2;
System.out.println("나눗셈 결과는 "+result);
return true;
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
return false;
}
finally
{
System.out.println("finally 영역 실행");
}
}
}
8. 나이를 입력 받았을 때 0보다 작은 값이 입력되면은
"유효하지 않은 나이가 입력되었습니다."라고 출력하도록 예외처리를 만드시오.
A.
import java.util.Scanner;
class AgeInputException extends Exception
{
public AgeInputException()
{
super("유효하지 않은 나이가 입력되었습니다.");
}
}
class ProgrammerDefineException
{
public static void main(String[] args)
{
System.out.print("나이를 입력하세요: ");
try
{
int age=readAge();
System.out.println("당신은 "+age+"세입니다.");
}
catch(AgeInputException e)
{
System.out.println(e.getMessage());
}
}
public static int readAge() throws AgeInputException
{
Scanner keyboard=new Scanner(System.in);
int age=keyboard.nextInt();
if(age<0)
{
AgeInputException excpt=new AgeInputException();
throw excpt;
}
return age;
}
}
9. ( )는 예외상황이 발생되었음을 자바 가상머신에게 알리는 키워드이다.
따라서 이 문장이 실행되면서 자바의 예외처리 매커니즘이 동작하게 된다.
A. throw
10. 문제8번을 메소드를 쓰지않고서 메인메소드내에서 처리해 보자.
A.
import java.util.Scanner;
class AgeInputException extends Exception
{
public AgeInputException()
{
super("유효하지 않은 나이가 입력되었습니다.");
}
}
class ProgrammerDefineException
{
public static void main(String[] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.print("나이를 입력하세요: ");
try
{
int age=keyboard.nextInt();
if(age<0)
{
AgeInputException excpt=new AgeInputException();
throw excpt;
}
System.out.println("당신은 "+age+"세입니다.");
}
catch(AgeInputException e)
{
System.out.println(e.getMessage());
}
}
}
11. 문제 8번의 main메소드 내에서도 예외상황을 처리하지 않는다면 어떻게 해야 되는가?
A.
import java.util.Scanner;
class AgeInputException extends Exception
{
public AgeInputException()
{
super("유효하지 않은 나이가 입력되었습니다.");
}
}
class ThrowsFromMain
{
public static void main(String[] args) throws AgeInputException
{
System.out.print("나이를 입력하세요: ");
int age=readAge();
System.out.println("당신은 "+age+"세입니다.");
}
public static int readAge() throws AgeInputException
{
Scanner keyboard=new Scanner(System.in);
int age=keyboard.nextInt();
if(age<0)
{
AgeInputException excpt=new AgeInputException();
throw excpt;
}
return age;
}
}
12. 가상머신의 예외처리 방식
A.
① getMessage 메소드를 호출한다.
② 예외상황이 발생해서 전달되는 과정을 출력해준다.
③ 프로그램을 종료한다.
13. 예외가 발생해서 전달되는 과정이 출력되는 메소드.
( ) 클래스에 정의되어 있는 ( ) 메소드가 이러한 유형의 메시지를 출력
A. ( Throwable ) 클래스에 정의되어 있는 ( printStackTrace ) 메소드가 이러한 유형의 메시지를 출력
14. 이름과 나이를 입력받아 저장할려고 한다.
이름은 두 글자 이상을 입력받아야 한다.
(예외클래스에는 잘못된 이름을 저장할 수 있는 인스턴스 변수와 그 잘못된 이름을 출력하는 메소드를 만들자.)
나이는 음수값이 입력되면 안된다.
그리고 13번에 있는 메소드를 이용하여 예외상황이 전달되는 과정을 출력하도록 하자.
A.
import java.util.Scanner;
class AgeInputException extends Exception
{
public AgeInputException()
{
super("유효하지 않은 나이가 입력되었습니다.");
}
}
class NameLengthException extends Exception
{
String wrongName;
public NameLengthException(String name)
{
super("잘못된 이름이 삽입되었습니다.");
wrongName=name;
}
public void showWrongName()
{
System.out.println("잘못 입력된 이름: "+ wrongName);
}
}
class PersonalInfo
{
String name;
int age;
public PersonalInfo(String name, int age)
{
this.name=name;
this.age=age;
}
public void showPersonalInfo()
{
System.out.println("이름: "+name);
System.out.println("나이: "+age);
}
}
class PrintStackTrace
{
public static Scanner keyboard=new Scanner(System.in);
public static void main(String[] args) throws AgeInputException
{
try
{
PersonalInfo readInfo=readPersonalInfo();
readInfo.showPersonalInfo();
}
catch(AgeInputException e)
{
e.printStackTrace();
}
catch(NameLengthException e)
{
e.showWrongName();
e.printStackTrace();
}
}
public static PersonalInfo readPersonalInfo()
throws AgeInputException, NameLengthException
{
String name=readName();
int age=readAge();
PersonalInfo pInfo=new PersonalInfo(name, age);
return pInfo;
}
public static String readName() throws NameLengthException
{
System.out.print("이름 입력: ");
String name=keyboard.nextLine();
if(name.length()<2)
throw new NameLengthException(name);
return name;
}
public static int readAge() throws AgeInputException
{
System.out.print("나이 입력: ");
int age=keyboard.nextInt();
if(age<0)
throw new AgeInputException();
return age;
}
}
15. Throwable을 상속하는 예외 클래스는 ( )과 ( ) 두 가지이다.
( )는 그 이름이 의미하듯이 단순히 예외라고 하기에는 심각한 오류의 상황을 표현하기 위해 정의된 클래스이다.
따라서 이 클래스를 상속하여 정의된 클래스는(이는 프로그래머가 정의하는 클래스가 아니다.)
프로그램의 실행을 멈춰야 할 정도의 매우 심각한 오류상황을 표현하는데 사용이 된다.
( )를 상속하는 대표적인 클래스의 이름은 ( ) 이다.
API 문서에서는 이 클래스에 대해서 다음과 같이 설명한다.
"자바 가상머신에 문제가 생겨서 더 이상 제대로 동작할 수 없는 상황을 알리기 위해서 정의된 클래스입니다."
( )를 상속하는 클래스의 오류상황이 발생하면, 그냥 프로그램이 종료되도록 놔두는 것이 상책이다
(프로그램이 종료된 뒤 소스코드를 수정하는 등의 방식으로 원인을 해결해야 한다.)
( )의 하위 클래스
( )를 상속하는 대표적인 클래스가 ( )이다.
그리고 이를 상속하는 클래스 중에서 ( )라는 클래스가 있는데,
이는 메모리 공간이 부족한 상황을 표현하는 예외 클래스이다.
따라서 이러한 오류가 발생하면, 메모리가 효율적으로(또는 적절히) 사용되도록 소스코드 자체를 변경해야 한다.
이렇듯 Error와 관련 있는 오류상황은 소스코드의 변경을 통해서 해결해야 하는 경우가 대부분이다.
A.
Throwable을 상속하는 예외 클래스는 ( Exception )과 ( Error ) 두 가지이다.
( Error )는 그 이름이 의미하듯이 단순히 예외라고 하기에는
심각한 오류의 상황을 표현하기 위해 정의된 클래스이다.
따라서 이 클래스를 상속하여 정의된 클래스는(이는 프로그래머가 정의하는 클래스가 아니다.)
프로그램의 실행을 멈춰야 할 정도의 매우 심각한 오류상황을 표현하는데 사용이 된다.
( Error )를 상속하는 대표적인 클래스의 이름은 ( VirtualMachineError ) 이다.
API 문서에서는 이 클래스에 대해서 다음과 같이 설명한다.
"자바 가상머신에 문제가 생겨서 더 이상 제대로 동작할 수 없는 상황을 알리기 위해서 정의된 클래스입니다."
( Error )를 상속하는 클래스의 오류상황이 발생하면, 그냥 프로그램이 종료되도록 놔두는 것이 상책이다
(프로그램이 종료된 뒤 소스코드를 수정하는 등의 방식으로 원인을 해결해야 한다.)
( VirtualMachineError )의 하위 클래스
( Error )를 상속하는 대표적인 클래스가 ( VirtualMachineError )이다.
그리고 이를 상속하는 클래스 중에서 ( OutOfMemoryError )라는 클래스가 있는데,
이는 메모리 공간이 부족한 상황을 표현하는 예외 클래스이다.
따라서 이러한 오류가 발생하면, 메모리가 효율적으로(또는 적절히) 사용되도록 소스코드 자체를 변경해야 한다.
이렇듯 Error와 관련 있는 오류상황은 소스코드의 변경을 통해서 해결해야 하는 경우가 대부분이다.
16. Exception을 상속하는 대표적인 클래스 두가지
A. RuntimeException, IOException
17. Exception을 상속하는 클래스의 예외 상황이 임의의 메소드 내에서 발생 가능하다면,
해당 메소드는 반드시 다음 두 가지 중 한가지 방법을 선택해서 정의되어야 한다.
A.
① try~catch문을 이용해서 메소드 내에서 예외를 처리하도록 정의한다.
② throws를 이용해서 메소드를 호출한 영역으로 예외가 전달되도록 정의한다.
18.
clone(Object 클래스의 인스턴스 메소드)
protected Object clone()
throws CloneNotSupportedException
Creates and returns a copy of this object.
The precise meaning of "copy" may depend on the class of the object.
위의 메소드를 호출할 때 다음과 같이 호출하면 문제가 발생한다. 무엇이 문제인가?
public void simpleMethod(int n)
{
MyClass my = new MyClass();
my.clone();
...
}
A.
① 다음과 같이 try~catch를 삽입하거나
public void simpleMethod(int n)
{
MyClass my = new MyClass();
try
{
my.clone();
}
catch(CloneNotSupportedException e) { ... }
...
}
② 다음과 같이 throws에 의해서 던져짐을 명시해야 컴파일이 된다.
public void simpleMethod(int n) throws CloneNotSupportedException
{
MyClass my = new MyClass();
my.clone();
........
}
19. 처리하지 않아도 되는 ( )의 하위 클래스
Exception의 하위 클래스 중에는 ( )이라는 클래스가 존재한다.
그런데 이 클래스는 그 성격이 Error 클래스와 비슷하다.
(이는 Exception을 상속하는 다른 예외 클래스들과의 차이점이다)
( )을 상속하는 예외 클래스도 Error를 상속하는 예외 클래스와 마찬가지로
try~catch문, 또는 throws절을 이용한 예외처리를 필요로 하지 않는다.
하지만 다음과 같이 Error의 하위 클래스들과 구분되는 특징이 있다.
- ( )을 상속하는 예외 클래스는 Error를 상속하는 예외 클래스처럼 치명적인 상황을 표현하지 않는다.
- 따라서 예외발생 이휴에도 프로그램의 실행을 이어가기 위해서 try~catch 문으로 해당 예외를 처리하기도 한다.
A.
처리하지 않아도 되는 ( RuntimeException )의 하위 클래스
Exception의 하위 클래스 중에는 ( RuntimeException )이라는 클래스가 존재한다.
그런데 이 클래스는 그 성격이 Error 클래스와 비슷하다.
(이는 Exception을 상속하는 다른 예외 클래스들과의 차이점이다)
( RuntimeException )을 상속하는 예외 클래스도 Error를 상속하는 예외 클래스와 마찬가지로
try~catch문, 또는 throws절을 이용한 예외처리를 필요로 하지 않는다.
하지만 다음과 같이 Error의 하위 클래스들과 구분되는 특징이 있다.
- ( RuntimeException )을 상속하는 예외 클래스는 Error를 상속하는 예외 클래스처럼 치명적 상황을 표현하지 않는다.
- 따라서 예외발생 이휴에도 프로그램의 실행을 이어가기 위해서 try~catch 문으로 해당 예외를 처리하기도 한다.
20. 19번 클래스를 상속하는 클래스들은 무엇이 있는가?
A.
- ArrayIndexOutOfBoundsException
- ClassCastException
- NegativeArraySizeException
- NullPointerException
예외의 성격이 보여주듯이 특별한 경우가 아니면,
이들에 대해서는 try~catch문을 이용해서 예외처리를 하지 않는다.
'SW > Java' 카테고리의 다른 글
[필기정리]Day19 - equals(), clone() 등 (0) | 2020.07.06 |
---|---|
[필기정리]Day18 - 전화번호 관리 프로그램 문제 06단계 (0) | 2020.07.03 |
[필기정리]Day16 - 인터페이스, 전화번호 관리 프로그램 문제 05단계 (0) | 2020.07.01 |
[필기정리]Day15 - Lotto생성기 및 숫자야구게임 문제 (0) | 2020.06.30 |
[필기정리]Day14 - 전화번호 관리 프로그램 문제 04단계 (0) | 2020.06.29 |