Data Scientist 옌

매일 발전하는 IT문제해결사

국비지원교육 (22.01-22.07)/강의노트

22-02-22(화) 019일차 [Java] 예외처리

옌炎 2022. 4. 20. 02:06
728x90

수업내용


1교시 (09:30-10:20)

  • 지난 수업 복습
프로그램에서 제일 중요한 것은 
변수 
함수 

===================================
자바 프로그램에서 최소 단위 는 클래스 이다.
클래스 구성원 = 변수 + 함수 
===================================

변수 
	지역변수
	멤버변수
		데이터자료형
			기초자료형
				값 리터럴 literal 숫자(정수, 실수) 문자 논리값(true, false) 63쪽
			참조자료형
				값을가르키는 주소값

ArrayList
1. 객체 배열 Object Array
2. 데이터 타입이 동일하지 않아도 된다.
3. 길이를 정하지 않아도 된다.		ArrayList aList = new ArrayList(10);
4. 데이터가 많을 때 사용한다.

자바 배열
1. 배열은 객체이다.		int i[] = new int[];
2. 데이터 타입이 동일해야 한다.
3. 길이가 정해져 있어야 한다.		int i[] = new int[3];
4. 적은 량의 데이터에서 사용한다.

배열 과 ArrayList 는 index 를 갖는다. 


java.lang.Object

java.lang.Object.toString()
	getClass().getName() + '@' + Integer.toHexString(hashCode());
	오버라이딩해서 내용을 변경할 수 있다.

java.lang.Object.equals() : 주소값 비교
java.lang.String.equals() : 문자열 비교
java.lang.Integer.equals() : 정수값 비교 
 
== 상등연산자 : 숫자 비교
equals() 이퀄함수 : 문자열 비교 

String s = "abc";
String s1 = "abc";
boolean b = s == s1; true


앱 : App : Application 의 약자 : 응용 프로그램
  • Exam_Invoke
package a.b.c.ch5;


public class Exam_Invoke {
	
	// 기본 생성자
	Exam_Invoke() {
		System.out.println("Exam_Invoke() 생성자 >>> : ");
		
		// aM() 함수를 호출한다.
		aM();
	}
	
	void aM() {
		System.out.println("aM() 함수 >>> : ");
		
		// bM() 함수를 호출한다.
		bM();
	}
	
	void bM() {
		System.out.println("bM() 함수 >>> : ");
		
		// cM() 함수를 호출한다.
		cM();
	}
	
	void cM() {
		System.out.println("cM() 함수 >>> : ");
		// aM(); <-- 오류!
	}
	
	// main() 함수는 프로그램의 시작점이다.
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// Exam_Invpoke() 생성자를 호출한다. invoke 한다.
		new Exam_Invoke();
	}
}

2교시 (10:30-11:20)

  • [교재 487p] 예외처리
    • Exam_Exception
      • ctl + shift + esc : 작업관리자 창 열기
        • 세부정보 > 컬럼 우클릭 > 열 선택
        • 핸들, 스레드, I/O 읽기, I/O 쓰기 체크-> 여기서 스레드가 함수
        • 만약 100개의 스레드 중 한 개가 중지되면 모든 스레드를 중지해야하는가? 그렇지 않으므로 예외처리가 필요하다.
      package a.b.c.ch5;
      
      public class Exam_Exception {
      
      	public static void main(String[] args) {
      		// TODO Auto-generated method stub
      		// x, y 값을 명령행 인수로 받기 String[] args = {"", ""};
      		
      		// 예외처리를 했다.
      		try {
      			
      			String args0 = args[0];
      			String args1 = args[1];
      			
      			int x = Integer.parseInt(args0);
      			int y = Integer.parseInt(args1);
      			
      			int z = x + y;
      			
      			System.out.println("x + y = " + z);
      
      		} catch(Exception e) {
      			System.out.println("에러가 >>> : " + e.getMessage());
      		}
      
      		System.out.println("더하기 프로그램을 만들었다. >>> : ");
      	}
      
      }
      

3교시 (11:30-12:20)

  • [교재 487~8p] 예외처리
프로그램을 수행하는 중에 어떤 문제가 발생했을 때
그 프로그램을 중단할 것인지 계속 수행할 것인지

예외			Throwable 
중단			Error 클래스
계속 수행		Exception 클래스

예외를 처리하는 키워드
try ~ catch ~ finally 구문
	: 예외를 처리하는 구문 
	: 예외가 발생해도 프로그램을 정상 수행하기 위해서 사용
throws
	: 예외를 던지는 키워드 : 호출한 순서의 반대로
throw
	: 예외를 발생시키는 키워드

try {

	예외가 발생이 될 수 있는 구문을 적는다.

} catch(예외가 발생하면 해당하는 예외 클래스를 선언한다.) {

} finally {
	예외가 발생하든, 발생하지 않든 항상 수행되는 블록
	생략이 가능하다.
}


throws
	함수 뒤에 선언해서 사용한다.
	public void 함수이름()  throws 예외클래스 {
	
	}
  • Exam_TryCatch
package a.b.c.ch5;

public class Exam_TryCatch {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		try {
			int x = 1;
			int y = 0;
			
			int z = x / y;
			
			System.out.println("x / y = " + z);
		} catch(ArithmeticException e) {
			System.out.println("에러 로그 찍기 >>> : " + e);
		} finally {
			System.out.println("finally 블록 >>> : ");
			System.out.println("에러 또는 정상 모두 수행한다. >>> : ");
		}
		
		System.out.println("연산 후 수행되는 루틴이다. >>> : ");
	}
}

4교시 (12:30-13:20)

  • Exam_TryCatch_1
package a.b.c.ch5;

public class Exam_TryCatch_1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		try {
			
			String args0 = args[0];
			String args1 = args[1];
			
			int x = Integer.parseInt(args0);
			int y = Integer.parseInt(args1);
			
			int z = x / y;
			
			System.out.println("x / y = " + z);
		/*
		} catch(NumberFormatException n) {
			System.out.println("NumberFormatException :: 에러 로그 찍기 >>> : " + n);

		} catch(ArithmeticException a) {
			System.out.println("ArithmeticException :: 에러 로그 찍기 >>> : " a);
		*/	
		} catch(Exception e) {
			System.out.println("Exception :: 에러 로그 찍기 >>> : " + e);
			
		} finally {
			System.out.println("finally 블록 >>> : ");
			System.out.println("에러 또는 정상 모두 수행된다.");
		}
		System.out.println("연산 후 수행되는 루틴이다.");
	}
}

5교시 (14:30-15:20)

  • Exam_Throws
package a.b.c.ch5;

public class Exam_Throws {

	int aM() throws ArithmeticException {
		
		int z = bM();
		return z;
	}
	
	int bM() throws ArithmeticException {
		return 1 / 0;
	}
	/*
		main() 함수로 시작하는 프로그램에서
		함수의 호출 순서에 의해 수행되다가
		에러가 발생한 경우
		에러가 발생한 라인이 있는 함수부터
			에러를 던져서(throws) ~~
			main() 함수에서 예외처리를 하면 된다.
	*/
	
	// main() 함수가 시작점이다.
	// public static void main(String[] args) throws ArithmeticException {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Exam_Throws et = new Exam_Throws();
		int z = et.aM();
		
		System.out.println("z >>> : " + z);
	}
}
  • Exam_Throws_1
package a.b.c.ch5;

public class Exam_Throws_1 {
	
	int aM() throws Exception {
		
		int z = bM();
		
		return z;
	}
	
	int bM() throws Exception {
		
		int z = 0;
		
		z = 1 / 0;
		
		return z;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		try {
			Exam_Throws_1 et = new Exam_Throws_1();
			int z = et.aM();
			
			System.out.println("z >>> : " + z);
		} catch(Exception e) {
			System.out.println("에러가 e >>> : " + e);
		}
		
		System.out.println("try~catch 구문 이후 블록");
	}
}

6교시 (15:30-16:20)

  • Exam_ForName
package a.b.c.ch5;

import java.lang.reflect.Method;

public class Exam_ForName {
	
	public void classForName() throws ClassNotFoundException,
									  InstantiationException,
									  IllegalAccessException {
		
		// public static Class<?> forName(String className) throws ClassNotFoundException
		// a.b.c.ch5.Exam_Invoke
		Class c1 = Class.forName("a.b.c.ch5.Exam_Invoke");
		System.out.println("c1 >>> : " + c1);
		// public T newInstance() throws InstatiationException, IllegalAccessException
		Exam_Invoke ei = (Exam_Invoke)c1.newInstance();
		System.out.println("ei >>> : " + ei);
		ei.aM();
		ei.bM();
		ei.cM();
		
		// 클래스에 선언된 메소드 찾기
		Method m[] = c1.getDeclaredMethods();
		for (int i=0; i < m.length; i++) {
			String findM = m[i].getName();
			System.out.println("m[" + "].getName() >>> :: " + findM);
		}
	}

	public static void main(String[] args) throws ClassNotFoundException,
												  InstantiationException,
												  IllegalAccessException {
		// TODO Auto-generated method stub
		new Exam_ForName().classForName();
	}
}

7교시 (16:30-17:20)

  • Exam_ForName_1
package a.b.c.ch5;

import java.lang.reflect.Method;

public class Exam_ForName_1 {
	
	public void classForName() {
		
		try {
			Class c1 = Class.forName("a.b.c.ch5.Exam_Invoke");
			System.out.println("c1 >>> : " + c1);
			Exam_Invoke ei = (Exam_Invoke)c1.newInstance();
			System.out.println("ei");
			ei.aM();
			ei.bM();
			ei.cM();
			
			// 클래스에 선언된 메소드 찾기
			Method m[] = c1.getDeclaredMethods();
			for (int i=0; i < m.length; i++) {
				String findM = m[i].getName();
				System.out.println("m[" + i + "].getName() >>> :: " + findM);
			}
			
			Class d = Class.forName("java.util.Date");
			java.util.Date dd = (java.util.Date)d.newInstance();
			System.out.println("dd >>> : " + dd);
			
			Class aList = Class.forName("java.util.ArrayList");
			java.util.ArrayList aList_1 = (java.util.ArrayList)aList.newInstance();
			
			System.out.println("aList_1 >>> : " + aList_1);
		} catch(Exception e) {
			System.out.println("에러가 >>> : " + e);
		}
	}
	
	public static void main(String[] args) {

		// TODO Auto-generated method stub
		new Exam_ForName_1().classForName();
	}
}
  • [교재 378p] [380p] [384p]

8교시 (17:30-18:30)

  • [교재 379p] 컴파일된 클래스만!
    • ForName_1에서 Exam_Invoke 소스를 지워도 가능
  • [교재 507p] 사용자 정의 예외
  • Exam_Throw
package a.b.c.ch5;

public class Exam_Throw {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		try {
			throw new Exception("오류 메시지");
			// Exception e = new Exception("오류 메시지");
			// throw e;
			// 사용하지 말 것
		} catch(Exception e) {
			System.out.println("e >>> : " + e);
			// 공부할 때 에러 메시지는 getMessage() 함수로 출력한다.
			System.out.println("e.getMessage() >>> : " + e.getMessage());
			// e.printStackTrace();
		}

		System.out.println("try-catch 블럭 이후 >>> : ");
	}
}
  • Exam_Throw_1
package a.b.c.ch5;

@SuppressWarnings("serial")
class IDFormatException extends Exception {
	
	// 생성자
	public IDFormatException(String s) {
		super(s);
	}
}

class IDFormatTest {
	
	private String userID;
	
	public String getUserID() {
		return userID;
	}
	
	public void setUserID(String userID) throws IDFormatException {
		
		if (userID == null) {
			IDFormatException ide = new IDFormatException("아이디는 null일 수 없습니다.");
			throw ide;
		} else if (userID.length() < 8 || userID.length() > 20) {
			throw new IDFormatException("아이디는 8 ~ 20자 입니다.");
		}
		this.userID = userID;
	}
}

public class Exam_Throw_1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		IDFormatTest idt = new IDFormatTest();
		
		String userID = null;
		
		try {
			idt.setUserID(userID);
		} catch(IDFormatException i) {
			// System.out.println("i 에러가 >>> : " + i);
			System.out.println("i.getMessage() >>> : " + i.getMessage());
			// i.printStackTrace();
		}
		
		userID = "1234567";
		try {
			idt.setUserID(userID);
		} catch(IDFormatException i) {
			// System.out.println("i 에러가 >>> : " + i);
			System.out.println("i.getMessage() >>> : " + i.getMessage());
			// i.printStackTrace();
		}

		System.out.println("try-catch 블록 이후 >>> : ");
	}
}
  • 예외처리 확인
컴파일러에서
예외처리를 확인하는 예외클래스들은 Checked 예외
예외처리를 확인하지 않는 예외클래스들은 Unchecked 예외: RuntimeException
=======================================================================
			Checked Exception
=======================================================================
처리 여부		반드시 예외를 처리해야 함			명시적인 처리를 강제하지 않음

확인 시점		컴파일 단계					실행 단계

예외발생 시
트랜잭션 처리	roll-back 하지 않음			roll-back 함

대표 예외		Exception 클래스를			RuntimeException 하위 예외 클래스
			상속받은 하위 클래스 중			NullPointerException
			Runtime Exception을			IllegalArgumentException
			제외한 모든 예외 클래스			IndexOutOfBoundException
			IOException					SystemException
			SQLException
=======================================================================

Notes


728x90