2016년 8월 3일 수요일

Java 1-10 예외처리


public class MainEx1 {

public static void main(String[] args) {

int[] num = { 10, 20, 30};
for(int i = 0; i<=3; i++){
try {
// 예외가 발생할 수 있는 상황이 들어간다.
System.out.println("num["+i+"] : "+num[i]);
} catch (ArrayIndexOutOfBoundsException e) { // 예외 발생상황 적어주기.
// 예외 발생할때 여기로 넘어온다.
// 배열 넘침
System.out.println("error : "+e);
} catch(Exception e){
// 알수 없는 에러 발생
System.out.println("error : "+e);
}

}

}

}
-----------------------------------------------------------------------------
import java.io.IOException;

class CharInput {
int input;
public char getInput() throws IOException{
input = System.in.read();
return (char)input;
}
}

public class MainEx2 {

public static void main(String[] args) {

CharInput ci = new CharInput();
System.out.println(ci.getInput());

}

}
----------------------------------------------------------------------------------
class MyException extends Exception{
public MyException() { super(); }
public String toString() { return "MyException입니다";}
}

class MyExceptionTest{
// 예외발생하면 MyException 던진다.
public void testFunc(int x) throws MyException{
// x가 10초과하면 MyException던진다.
if(x>10) { throw new MyException(); }
// x가 10이하이면 x 출력
else { System.out.println(x); }
}
}


public class MainEx3 {

public static void main(String[] args) {

// MyExceptionTest 객체 생성
MyExceptionTest test1To20 = new MyExceptionTest();
// MyExceptionTest클래스의 testFunc메서드 실행 (매개변수 1~19)
for(int i=0;i<20;i++){
System.out.println("i는 "+i+"입니다.");
try {
test1To20.testFunc(i);
} catch (MyException e) {
System.out.println(e);
}
}

}

}

댓글 없음:

댓글 쓰기