try 안에 에러가 발생할 수 있는 부분을 넣음
사용은 많이 하지만 직접 만들지는 않음
if로 대부분의 예외처리함
try{
에러발생 할 수 있는 코드
} catch(Exception e){
해결방안
e.printStackTrace(); // 어떤 에러인지 확인 //자세한 예외정보출력
}
public class ExException_01 {
public static void main(String[] args) {
System.out.println("프로그램 시작!!!");
//try 안에 에러가 발생할 수 있는 부분을 넣음
//사용은 많이 하지만 직접 만들지는 않음
//if로 대부분의 예외처리함
try {
//에러발생 할 수 있는 코드
int num=3/0; //오류 일부러 발생 //정수를 0으로 나누면 에러발생
//catch(~~때문에 나는 오류 e(변수))
//에러에 대한 해결.처리
} catch(ArithmeticException e) {
//해결방안
System.out.println(e.getMessage()); //예외 출력메세지
//e.printStackTrace(); // 어떤 에러인지 확인 //자세한 예외정보출력
}
System.out.println("프로그램 종료");
}
}
public class NullPoint_02 {
//NullPointerExcetion - 생성하지 않고 클래스의 메소드를 호출하는 경우
Date date;
public void writeday() {
int y,m,d;
//예외처리 안하고 넘어갈게
//위기 상황을 모면하는 것
try {
y=date.getYear()-1900;
m=date.getMonth()+1;
d=date.getDate();
System.out.println(y+"년"+m+"월"+d+"일입니다");
//모든 exception의 부모 -> Exception
}catch (NullPointerException e) {
System.out.println("객체생성을 안했어요"+e.getMessage());
}
}
public static void main(String[] args) {
NullPoint_02 np=new NullPoint_02();
np.writeday();
System.out.println("***정상종료***");
}
}
결과물
객체생성을 안했어요Cannot invoke "java.util.Date.getYear()" because "this.date" is null
***정상종료***
Stream은 한글 1글자의 바이트도 못 넣음
1바이트만 가능
oracle 사용하면 안해도됨
InputStream 변수=System.in;
try {
변수=is.read();//읽어오는 것//처리안하면 무조건 오류가 나서 빨간줄발생
} catch (IOException e) { //multicatch - catch가 하나 더 옴
e.printStackTrace();//어디서 에러가 나는지 확인하기 위한 것
System.out.println("오류: "+e.getMessage());
}
Thread 발생하면 무조건 try/catch 처리
try {
Thread.sleep(3000); //몇 초 할건지
} catch (InterruptedException e) {
e.printStackTrace();
}
public class FileException_03 {
public static void main(String[] args) {
//Stream은 한글 1글자의 바이트도 못 넣음
//1바이트만 가능
//oracle 사용하면 안해도됨
InputStream is=System.in;
int a=0;
System.out.println("한글자 입력:");
try {
a=is.read();//읽어오는 것//처리안하면 무조건 오류가 나서 빨간줄발생
//multicatch - catch가 하나 더 옴
} catch (IOException e) {
//e.printStackTrace();//어디서 에러가 나는지 확인하기 위한 것
System.out.println("오류: "+e.getMessage());
}
System.out.println("***3초 뒤 출력***");
//Thread 발생하면 무조건 try/catch 처리
try {
Thread.sleep(3000); //몇 초 할건지
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("입력값: "+(char)a);
}
}