정보보안공부
Java2_day01 본문
*** NullPointerExample
-> data = null 일때 System.out.println(data.toString()); 은 오류 발생
-> Exception발생할 수 있는 부분을 블럭처리한다.
try { data = null; System.out.println(data.toString()) }
catch로 Exception 처리
catch(Exception e) { System.out.println("예외처리 합니다.") }
*** ExceptionTest
-> (int)(Math.random() * 10) 이 0이나올경우 exception발생
-> Exception발생할 수 있는 부분을 블럭처리한다.
try { result = number / (int)(Math.random() * 10 System.out.println(result) }
catch로 Exception 처리
catch(Exception e) { }
*** ThrowsMethod
-> try, catch 없이 실행할경우 ClassNotFoundException 이라는 에러발생
해당 클래스가 존재하지 않는다. 는 예외발생한다.
-> try { Class c = Class.forName("java.lang.Cloneable");
System.out.println(c.toString()); }
-> catch (Exception e) { System.out.println("해당 클래스가 존재하지 않습니다."); }
Exception 대신 ClassNotFoundException을 사용해도 된다.
*** ThrowsMethod2
-> static void findClass() throws Exception {
Class c = Class.forName("java.lang.Cloneable");
System.out.println(c.toString()); Exception처리를 호출한 main으로 넘긴다.
*** Account
-> private long 형으로 balance; 선언
-> private형이기때문에 public long getBalance() { return balance; } 선언
-> public void deposit(int money) { balance += money; } 입금메소드 선언
-> public void withdraw(int money) throws InsufficientException 출금메소드 선언
{ if ( balance < money ) throw new InsufficientException
("잔고부족 : " + (money-balance) + " 모자람" ); } balance -= money;
*** AccountExample
-> Accont account = new Account(); 객체 생성
-> account.deposit(100000); 예금선언후 예금액 출력
-> try{ account.withdraw(110000); 이면 catch 실행 100000 이하이면 예금액만 출력
-> catch(InsufficientException e) { String message = e.getMessage();
System.out.println(message); }
e.getMessage 로 throw new InsufficientException(~~) ~~을 불러온다.
*** InsufficientException
-> public class InsufficientException extends Exception 사용자 정의 예외 선언
-> public InsufficientException() { }
-> public InsufficientException(String message) { super(message); }
'Language > Java2' 카테고리의 다른 글
Java2_day06 (0) | 2017.03.17 |
---|---|
Java2_day05 (0) | 2017.03.16 |
Java2_day04 (0) | 2017.03.16 |
Java2_day03 (0) | 2017.03.14 |
Java2_day02 (0) | 2017.03.11 |