2022. 11. 25. 17:11ㆍJAVA
예외처리
예외처리란?
프로그램 실행 시 발생할 수 있는 예기치 못한 예외의 발생에 대비한 코드를 작성하는 것
목적 :
예외 발생 시 실행중인 프로그램의 갑작스런 비정상 종료를 막고.
비정상 종료를 막아 정상적인 실행상태를 유지할수 있도록 하는 것.
프로그램이 실행되는 도중 발생하는 예외를 처리하기 위해
try/ catch/ finally 문을 사용
try(
예외를 처리하길 원하는 실행코드;
}
catch(Exception1 e1){
Exception1이 발생했을 경우, 처리하기 위한 문장
}
catch(Exception2 e2){
Exception2이 발생했을 경우, 처리하기 위한 문장
}
.........
finally{ (finally는 선언해도되고 안해도 된다)
예외발생 여부와 상관없이 무조건 실행될 코드
}
문법)
public class Exception1125 {
public static void main(String[] args) {
// 예외처리
try
{
int[] a = {2,0};
int b =4;
int c = b / a[1];
System.out.println(c);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("배열 인덱스 오류 발생");
}
catch(ArithmeticException e)
{
System.out.println("0으로 나눌 수 없습니다. " +e);
}
finally
{
System.out.println("무조건 실행됨.");
}
System.out.println("예외처리 종료 후 처리됨.");
}
}
출력

예외 발생 시 실행중인 프로그램의 갑작스런 비정상 종료를 막고.
비정상 종료를 막아 정상적인 실행상태를 유지할수 있도록 하는 것.
프로그램이 실행중 어떤 원인에 의해서 오작동을 하거나
비정상적으로 종료되는 경우를 프로그램 에러 또는 오류라고 함.
컴파일 에러 : 컴파일 시에 발생하는 에러
런타임 에러 : 실행 시에 발생하는 에러
논리적 에러 : 실행은 되지만, 의도와는 다르게 동작하는 것
자바에서 실행 시 발생할 수 있는 프로그램 오류
- 에러(error) : 프로그램 코드에 의한 수습될 수 없는 심각한 오류
- 예외(exception) : 프로그램 코드에 의해서 수습될 수 있는 오류
예외가 발생하더라도 프로그래머가 이에 대한 적절한 코드를 미리 작성해 놓아
프로그램이 비정상적으로 종료되는 것을 막는것을 의미함
try, catch블럭안에 return이 있어도 finally블럭은 실행된다.
예제1)
public class Exception1125_5 {
public static void main(String[] args) {
method1();
System.out.println("mathod1() 실행 후 main출력");
}
static void startIntall()
{
System.out.println("프로그램 설치에 필요한 준비작업하는 영역");
}
static void copyFiles()
{
System.out.println("파일복사 영역");
}
static void deleteTempFiles()
{
System.out.println("임시파일 삭제영역");
}
static void method1()
{
try
{
System.out.println("method1() 실행");
return;
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("method() finally 블럭 실행");
}
}
}
출력1

예외클래스 계층구조 :모든 예외 최고 조상은 Exception 클래스

FileNotFoundException : 존재하지 않는 파일 이름 입력시 발생
ClassNotFoundExecption : 클래스 이름 오류
DataFarmatException : 입력한 데이터 형식 오류
ArrayindexOutOfBoundsExcrption : 배열의 범위를 벗어난 경우
NullPointerException : null인 참조변수의 멤버 호출하는 경우
ClassCastException : 클래스의 형변환을 잘못한 경우 발생
ArithmeticException : 정수를 0으로 나누려고 하는 경우
예제2) try ~ catch문의 실행 순서
public class Exception1125_3 {
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 e)
{
e.printStackTrace();
System.out.println("예외처리 : " + e.getMessage());
}
catch(Exception e)
{
System.out.println("Exception");
}
System.out.println(5);
}
}
출력2

예제3)파일 설치시 발생할 수 있는 예외 핸들링
예외 처리용 클래스 정의
class SpaceException extends Exception
{
public SpaceException(String msg)
{
super(msg); // = new Exception(msg);
}
}
class MemoryException extends Exception
{
MemoryException(String msg)
{
super(msg);
}
}
메인클래스
public class Exception1125_6 {
public static void main(String[] args) {
//예외처리 (사용자정의 예외)
try
{
startInstall();
copyFiles();
}
catch (SpaceException e)
{
System.out.println("에러 메세지 : " + e.getMessage());
e.printStackTrace();
}
catch(MemoryException e)
{
System.out.println("에러 메세지 : " + e.getMessage());
e.printStackTrace();
}
finally
{
deleteTempFiles();
}
}
static void startInstall() throws SpaceException, MemoryException
{
if(!enoughSpace())
{
throw new SpaceException("설치공간 부족");
}
if(!enoughMemory())
{
throw new MemoryException("메모리 부족");
}
}
static void copyFiles()
{
System.out.println("설치에 필요한 파일 복사");
}
static void deleteTempFiles()
{
System.out.println("임시 설치 파일 삭제");
}
static boolean enoughSpace()
{
//설치 공간이 충분한지 체크 적용
return false;
}
static boolean enoughMemory()
{
//설치 시 필요한 메모리공간 확인 적용
return true;
}
}
출력3

'JAVA' 카테고리의 다른 글
| 2022.11.29 JAVA 24일차 Object 클래스, String 클래스, Calender클래스, SimpleDateFormat (0) | 2022.11.29 |
|---|---|
| 2022.11.28 JAVA 23일차 예외처리(try ~ catch ~ finally)2 (0) | 2022.11.28 |
| 2022.11.24 JAVA 21일차 인터페이스 (0) | 2022.11.24 |
| 2022.11.23 20일차 Vector클래스, 추상화클래스 (0) | 2022.11.23 |
| 2022.11.22 JAVA 19일차 다형성 (0) | 2022.11.22 |