오늘은 시험보고 남은 시간 코드로 쳐보면서 수업을 진행하였다
주석처리 해놓고 구분해놓았으니 미래의 나는 복습 할 때 참고
package ex_01;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class TTT {
//-------------------------------------------throws------------------------------------
public static void main(String[] args)
throws FileNotFoundException, ArrayIndexOutOfBoundsException {
// 해당 오류구문을 호출하는 곳에서 처리하게끔 떠넘긴다/ 여러개 선언 가능 /해결이 안될 경우 오류구문 발생
// Runtime Exception은 throws구문을 선언 하지않아도 자동으로 호출한 곳으로 떠넘긴다
// main메서드가 던지는 것을 마직막으로 받을 수 있는 구문
//FileNotFoundException => "Checked" Exception
//아래의 생성자를 호출하다가, 지정된 파일이 없으면, 어떻게 할래!?라고 개발자에게 알려줌
//2가지 중에 한가지를 선택하라고 강제:호출된 메소드에 throws 생성 or try-catch 생성
// FileInputStream fis = new FileInputStream("test");
//
//
// try(fis) {;;} // 자원(리소스)를 자동으로 닫아주는 블록
// ------------------------------------try - catch 기본---------------------------
try{ // 예외처리용 try 블록 ,그냥 try 블록은 단독 사용이 안된다.
String name = null;
System.out.println("예외 발생 구문 읽기 전에는 실행되고 출력됩니다.");
int nameLength = name.length(); //Runtime Exception(실행중 발생하는 예외가 발생)
//NullPointerException 발생 -> 예외구문 생성 -> JVM 정지
//자바에서는 , 예외가 발생하면, 이 예외를 표현하는 "(예외)객체"를 만들어 표현한다.
System.out.println(nameLength);
System.out.println("예외 발생 구문 후에는 출력이 안됩니다. ");
} catch (NullPointerException e) {//매개변수 선언부에 Throwable을 포함한 자식들이 와야함
System.out.println("예외인 ("+e+")를 catch구문에서 꽉 잡았습니다."); //예외가 생겼을 때 해당문구 출력
}// try - catch ->>여러개 사용도 가능!
//-------------------------------------------다중 catch-------------------------------------
try {
int[] arr = { 1,2,3 };
System.out.println(arr[4]);
}catch (NullPointerException e) {
System.out.println("예외인 ("+e+")를 catch구문에서 꽉 잡았습니다.");
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("예외인 ("+e+")를 catch구문에서 꽉 잡았습니다.");
}//try - catch - catch >> 다중 catch
//예외에따라 다른 로직을 실행을 할 때
// 유의사항 - 예외객체가 상속관계일때는 부모타입을 더 나중에 catch 해야한다.
//------------------------------------------Multi-catch------------------------------------
try {
int[] arr = { 1,2,3 };
System.out.println(arr[4]);
}catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
System.out.println("예외인 ("+e+")를 catch구문에서 꽉 잡았습니다.");
} // -2종류중 어떤 예외가 발생하든 "같은" 예외 처리를 하겠다!
// 이 catch 문장을 이때에는 , "Multi-catch"라고 부른다.
//------------------------------------------throw-----------------------------------
// throw new Exception; // 고의로 해당 메서드에 예외 발생
} // main
}// end class
package ex_01;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
public class TTTT {
// 계좌이체 업무 수행 예제
public static void main(String[] args) {
Account myAccount = new Account("001-234-1100", 300);
Account targetAccount = new Account("003-001-0001", 0);
//예외 블록의 최소 구성은 반드시 (1)try-catch이거나 (2) try-finally 이어야한다.
//계좌이체 수행
try {
boolean isTransfered = myAccount.transfer(targetAccount, 500);
if(isTransfered) { //계좌이제 성공하면...
System.out.println("성공");
} //if
} catch (InvalidAccountException | InsufficientBalanceException e) {
e.printStackTrace(); // 발생한 예외의 Stack Trace를 콘솔에 출력(기본처리)
;; //예외처리는 개발자 맘대로 하는게 아니라 비즈니스 로직에 따라 예외처리해야한다!!
System.out.println("실패");
} finally { // finally 는 한번만 써야한다.
System.out.println("내 계좌:" + myAccount);
System.out.println("니 계좌:" + targetAccount);
}// try - multi - catch - finally
}// Entry Point
}//end class
@Setter
@Getter
@ToString
class Account { //은행계좌
String number; //계좌번호
long balance; // 잔고
Account(String number, int balance){
this.number =number;
this.balance = balance;
}//constructor
boolean isValid() { // 계좌 유효성 검사
return true;
} // isValid
long deposit(long money) {
this.balance += money;
return this.balance;
} // deposit
long withdraw(long money) {
this.balance -= money;
return this.balance;
}// withdraw
//계좌이체 수행 메소드
boolean transfer(Account targetAccount,int transferMoney) throws InvalidAccountException, InsufficientBalanceException {
//1.소스/타겟계좌 유효성검사
if(this.isValid() && targetAccount.isValid()) { // 타겟 계좌가 유효하면 ...
//2.계좌이체 수행
if(this.balance >= transferMoney) { //잔고가 충분하면...
this.withdraw(transferMoney); //내계좌 출금
targetAccount.deposit(transferMoney);//이체계좌 입금
return true;
}else { //소스계좌에 이체금액보다 잔고가 적으면 ...
//4. 계좌 잔고가 부족함을 의미하는 직접 예외 발생시킴
throw new InsufficientBalanceException("잔고가"+this.balance+"원 남아 이체금액이 부족합니다.");
}//if -else
} else { //타겟 계좌가 유효하지 않으면 ...
// 3. 계좌가 유효하지 않음을 의미하는 예외 발생
throw new InvalidAccountException("계좌가 유효하지 않습니다.");
} // if -else
}//transfer
} // end class
//계좌가 유효하지 않음을 사용자 정의 예외 클래스 선언
class InvalidAccountException extends Exception {// Checked 예외
private static final long serialVersionUID = 1L;
public InvalidAccountException() {
super();
}// default constructor
public InvalidAccountException(String message) {
super(message);
} // constructor
}// end class
//잔고가 부족함을 사용자 정의 예외 클래스 선언
class InsufficientBalanceException extends Exception {// Checked 예외
private static final long serialVersionUID = 1L;
public InsufficientBalanceException() {
super();
}// default constructor
public InsufficientBalanceException(String message) {
super(message);
} // constructor
}// end class
아부지가 컴퓨터 써야한다고 보채서 급하게 정리하고 자리를 비운다.