Develop/JAVA

JAVA 예외처리

roalwh 2023. 10. 21. 18:54

 

//예외처리
//프로그램에 문제가 발생했을때 시스템 동작에 문제가 없도록 사전에 예방하는 코드를 작성하는 방법
/*
 * Exception -->  Error는 개발자가 대처할 수 있다.
 * Error --> Error는 개발자가 대처할 수 없음
 * Exception
 * Checked Exception --> 예외처리를 반듯이 해야하는 경우 (네트워크, 파일 시스템 등)
 * Unchecked Exception --> 예외처리를 개발자의 판단에 맞기는 경우 (데이터 오류 등)
 * Exception 클래스 하위클래스로 NullPointerException, NumberformatException, ArrayIndexOutOfBoundException 등이 있다.
 * NullPointerException --> 객체를 가리키지않고 있는 레퍼런스를 이용할때
 * NumberformatException  -->숫자데이터에 문자데이터 들을 넣었을때
 * ArrayIndexOutOfBoundException --> 배열에서 존재하지 않는 인덱스를 가리킬 때
 */
public class MainClass01 {
	
	
	public static void main(String[] args) {
		
		int i = 10;
		int j = 0;
		int r = 0;
		
		System.out.println("Exception BEFORE");
		
		
		//예외가 발생할 만한 구문을 try -catch 구분에 넣어준다.
		//개발자가 예외처리하기 가장 쉽고, 많이 사용되는 방법이다.
		try {
			r = i/j; //예외가 발생할 수 있는 코드
		} catch (Exception e) { //예외가 발생했을 때 처리할 코드
			e.printStackTrace(); //
			String msg = e.getMessage(); //예외를 간략히 출력
			System.out.println("msg : " + msg);
		}
		
		
		System.out.println("Exception AFTER");
	}
}
 
 
결과값
Exception BEFORE
msg : / by zero
Exception AFTER
java.lang.ArithmeticException: / by zero
	at MainClass01.main(MainClass01.java:29)
 
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;

public class MainClass02 {

	public static void main(String[] ars) {
		
		Scanner scanner = new Scanner(System.in);
		int i,j;
		ArrayList<String> list = null;
		
		int[] iArr = {0,1,2,3,4};
		
		System.out.println("Ecexxption Before");
		
		try {
			
			System.out.println("input i : ");
			i = scanner.nextInt();
			System.out.println("input j : ");
			j = scanner.nextInt();
			
			System.out.println( "i / j = " + i/j);
			
			for (int k = 0; k < 6 ; k++) {
				
				System.out.println( "iArr{" + k + "] : " + iArr[k]);
			}
			
			System.out.println("list.size() : " + list.size());
		 }
		//Exception 및 하위 클래스를 이용해서 예외처리를 다양하게 할 수 있다.
		catch (InputMismatchException e) {
			e.printStackTrace(); }
		catch (ArrayIndexOutOfBoundsException e) {
			e.printStackTrace(); }
		catch (Exception e) { e.printStackTrace();}
		
		System.out.println("Ecexption After");
		}
	}

 
결과값
Ecexxption Before
input i : 
1
input j : 
2
i / j = 0
iArr{0] : 0
iArr{1] : 1
iArr{2] : 2
iArr{3] : 3
iArr{4] : 4
java.lang.ArrayIndexOutOfBoundsException: 5
Ecexption After
	at MainClass02.main(MainClass02.java:28)
 
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;

public class MainClass03 {

	public static void main(String [] args) {
		
		Scanner scanner = new Scanner(System.in);
		int i,j;
		ArrayList<String> list = null;
		
		int[] iArr = {0,1,2,3,4};
		
		System.out.println("Ecexption Before");
		
		try {
			
			System.out.println("input i : ");
			i = scanner.nextInt();
			System.out.println("input j : ");
			j = scanner.nextInt();
			
			System.out.println( "i / j = " + i/j);
			
			for (int k = 0; k < 6 ; k++) {
				
				System.out.println( "iArr{" + k + "] : " + iArr[k]);
			}
			
			System.out.println("list.size() : " + list.size());
		} catch (InputMismatchException e) {
			e.printStackTrace(); 
		} catch (ArrayIndexOutOfBoundsException e) {
			e.printStackTrace(); 
		} catch (Exception e) { 
			e.printStackTrace();
		} finally {
			System.out.println("예외 발생 여부에 상관없이 언제나 실행 됩니다.");
		}
		
		
		System.out.println("Ecexption After");
	}
}
 
결과값
Ecexption Before
input i : 
1
input j : 
2
i / j = 0
iArr{0] : 0
iArr{1] : 1
iArr{2] : 2
iArr{3] : 3
iArr{4] : 4
java.lang.ArrayIndexOutOfBoundsException: 5
예외 발생 여부에 상관없이 언제나 실행 됩니다.
Ecexption After
	at MainClass03.main(MainClass03.java:28)
 
public class MainClass04 {

	public static void main(String[] args) {
		
		MainClass04 mainClass04 = new MainClass04();
		
		try {
			mainClass04.firstMethod();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	//예외 발생시 예외처리를 직접 하지 않고 호출한 곳으로 넘긴다.
	public void firstMethod() throws Exception {
		secondMethod();
	}
	
	public void secondMethod() throws Exception {
		thirdMethod();
	}
	
	public void thirdMethod() throws Exception {
		System.out.println("10 /0 = " + (10/0));
	}
}
 
결과값
java.lang.ArithmeticException: / by zero
	at MainClass04.thirdMethod(MainClass04.java:26)
	at MainClass04.secondMethod(MainClass04.java:22)
	at MainClass04.firstMethod(MainClass04.java:18)
	at MainClass04.main(MainClass04.java:9)
 

'Develop > JAVA' 카테고리의 다른 글

Stream  (0) 2023.12.18
JAVA 데이터 은닉  (0) 2023.10.21
JAVA 객체 패키지와 static  (0) 2023.10.21
JAVA 객체 생성자 소멸자 this키워드  (0) 2023.10.21
JAVA 객체와 메모리(레퍼넌스)  (0) 2023.10.21