try
{...}
catch(ExceptionClass1 e)
{...}
...
catch(ExceptionClassN e)
{...}
finally
{
	CodeToBeExecutedInAllCases
}​
throw new ExceptionClassName(SomeString);

Java library softeware는 비정상적인 동작이 발생 했을 때 신호를 보내는 체계를 갖고 있다.

이를 throwing an exception이라고 한다.

예외적인 상황을 처리하는 코드를 제공해야하는데 이를 hadling the exception이라고 한다.

 

try-throw-catch

Java에서는 기본적으로 try-throw-catch를 사용하여 exception handling을 한다.

try에서는 기본적인 코드를 수행한다.

try문에서는 exception을 throw하는 코드를 포함할 수 있다.

throw 되는 경우 이후의 try 문 수행은 중단되고 catch 문으로 넘어가게 된다.

 

throw statement는 함수 호출과 유사하다.

throw new ExceptionClassName(SomeString);

ExceptionClassName 클래스의 객체가 생성된다.

throw 문은 함수를 호출하는 대신 catch block을 불러온다.

 

exception이 throw 되면 catch block 이 실행되기 시작한다.

catch block의 실행을 cathcing the exeception 혹은 handling the exception이라고 한다.

catch(Exception e)
{
	ExceptionHandlingCode
}

e 는 catch block parameter이다.

이 매개변수는 두 가지 역할을 한다.

1.  thrown exception 객체의 유형을 구체화한다.

2. thrown exception 객체를 잡기 위한 이름으로 사용된다.

 

<try-throw-catch 예시>

try
{
	if(men == 0 && women == 0)
		throw new Exception("Lesson is canceled. No students.");
	else if (men ==0)
		throw new Exception("Lesson is canceled. No men. ");
	else if (women ==0)
		throw new Exception("Lesson is canceled. No women.");
        
	if (women >= men)
		System.out.println("Each man must dance with " + women/(double)men + "women.");
	else
		System.out.println("Each woman must dance with " + men/(double)women + "men.");
}
catch(Exception e)
{
	String message = e.getMessage();
	System.out.println(message);
	System.exit(0);
}

 

getMessage Method

...//method code
try
{
	...
	throw new Exception(StringArgument);
	...
}
catch(Exception e)
{
	String message = e.getMessage();
	System.out.println(message);
	System.exit(0);
}

모든 exception은 message를 포함한 String 인스턴스 변수를 갖는다. (주로 exception의 이유를 포함)

StringArgument는 Exception 생성자의 인자이다.

e.getMessage()는 해당 string을 반환하게 된다.

 

Multiple catch Blocks

try block 이후에 다른 유형의 exception을 잡는 catch block이 여러 개 올 수 있다.

catch block이 여러개인 경우 catch block은 순서대로 실행된다.

catch (Exception e)
{...}
catch (NegativeNumberException e)
{...}

위와 같은 경우 NegativeNumberException 이 Exception type에 해당하므로 첫번째 catch문에서 잡히기 때문에 두 번째 catch 문이 사용되지 않게 된다.

올바르게 동작하기 위해서는 두 catch block의 순서를 바꿔야 한다.

 

finally Block

finally block은 exception throw 여부와 관계없이 실행된다.

try
{. . .}
catch(ExceptionClass1 e)
{ . . .}
 . . .
catch(ExceptionClass2 e)
{. . .}
finally
{
	CodeToBeExecutedInAllCases
}

'Development > OOP(Java)' 카테고리의 다른 글

Ch8. Polymorphism and Abstract Classes  (0) 2023.05.08
Ch6. Defining Classes(3)  (0) 2023.04.10
Project1 (Timetable application)  (0) 2023.04.05
Ch3. Flow of Control  (0) 2023.04.04
Ch5. Defining Classes(2)  (0) 2023.04.03

+ Recent posts