예외: 프로그램 실행중에 발생하는 경미한 에러
예외처리: 예외가 발생되었을떄 이에 대한 적절한 처리를 하느것
형식)
try{
예외가 발생될 수 있는 실행문장;
..
}catch(예외타입 참조변수){
예외가 발생되었을때 수행할 문장;
...
}catch(예외타입 참조변수){
예외가 발생되었을때 수행할 문장;
..
}finally{
예외와 상관없이 무조건 수행해야 할 문장;
}
예외가 발생될 수 있는 문장을 try{}
블록으로 묶고 catch
절에서 예외에 따른 적절한 처리를 한다.
catch()
에 부모클래스가 위로 올라오면 안된다. 코드는 위에서 밑으로 실행되는데 위에 부모가있고 밑에 자식클래스가 있으면 실행이 안된다.?
Scanner scan = new Scanner(System.in);
while(true){ 루프실행
System.out.println("첫번째 수 입력(종료0)");
int n1 =scan.nextInt();
if(n1==0) 입력한 값이 0이면 종료
break;
System.out.println("두번째 수 입력");
int n2 = scan.nextInt();
try{ 예외가 발생할 수 있는 실행문장
int n3 = n1/n2;
System.out.println(n1+"/"+n2+"="+n3);
}catch{AritmeticException ae){
System.out.println("0으로 나눌수 없다.");
System.out.println("오류메세지:"+ae.getmessage());
continue;
}
}
}
}
정수를 0으로 나누게되면 AritmeticException
에러가 나타남 이를 방지하기 위해 Exception
발생시 실행 코드를 적어주면된다.
finally
는 필수요소가 아니다.
자바에서는 예외 처리 방법이 두가지 있다.
1. 예외가 발생될 수 있는 문장들을 직접 try
~catch
로 처리하기
2. 예외가 발생될 수 있는 문장들을 직접 처리하지 않고 throws
로 넘기기
Scanner scan = new Scanner(System.in);
System.out.println("첫번째 정수 입력");
int n1 = scan.nextInt();
System.out.println("두번째 정수 입력");
int n2 = scan.nextInt();
try{
int n3 = div(n1,n2); 👈🏻2
System.out.println("나누값"+n3);
}catch(AritmeticException ae){
System.out.println("0으로 나눌 수 없어요");
} 👇1
public static int div(int n1, int n2) throws ArihmeticException{
int n3 = n1/n2;
return n3;
}
throws는 현재메소드를 호출한 메소드로 예외를 던질수있다. 이때 메소드 뒤에 throw와 키워드를 붙여준다. 즉 1번을 2번으로 예외를 던진다.
checkedException
Exception
을 상속받지 않은 예외 클래스try
~catch
절로 예외 처리를 해야 하며 예외처리를 하지 않으면 컴파일시에 오류발생UnCheckedException
RuntimeException
을 상속받은 예외 클래스try
~catch
절로 예외 처리를 하지 않아도 컴파일시 에러가 발생되지 않으며 프로그래머가 선택적으로 예외 처리를 한다.데이터를 읽어로거나 출력에 관련된 작업
자바에서 데이터를 입출력 할때는 스트림을 사용한다.(스트림은 데이터의 흐름)
1byte
처리 스트림과 2byte
처리 스트림이 있다.
1byte
끝낼때 ~~~InputStream
,~~~InputStream
2byte
끝낼때 ~~~Reader
,~~~Writer
InputStream
클래스는 입력스트림의 최상위 추상클래스이고 1byte 처리 스트림이다.
//public static final InputStream in
InputStream is = System.in;
try{
//public abstract int read() throws IOException
System.out.println("딱 한글다만 입력")
int a = is.read();
System.out.println("입력된 문자"+(char)a);
}catch(IOException ie){
System.out.println(ie.getMessage())
}
InputStream is = System.in;
가 있기때문에 Scanner를 생략할 수 있다.
한글자의 영문만 입력가능한데 그 이유는 소문자나 대문자는 유니코드 값이 있기때문에 Integer
타입으로 선언하면 숫자로 저장된다. 그래서 출력할때는 char
로 강제 형변환을 해서 출력해야 입력한 영문이 나온다.
1바이트 처리 출력 스트림(출력스트림의 최상위 클래스)
추상클래스이므로 객체를 생성할 수 없다.
화면에 출력하기 위항 스트림 객체 얻어오기
OutputStream os = System.out;
try{
int b =65;
os.write(b);
os.flush(); //buffer가 다 채워지지않아도 데이터를 출력한다.
}catch(IOException ie){
System.out.println(ie.getMessage());
}
os.flush()
없이 출력을 하면 화면에는 아무것도 출력되지않는다. 출력될려면 buffer
를 사용해야하는데 전부 채워지지 않으면 출력하지않는다. 하지만 flush
를 쓰면 buffer
가 전부 채워지지않아도 출력이 된다.
FileOutputStream : 파일에서 1바이트 단위로 데이터를 출력하는 스트림클래스
try {
//public FileOutputStream(String name) throws FileNotFoundException
FileOutputStream fos = new FileOutputStream("c:\\java\\abc.txt"); //저장할위치
//int b = 65;
//public void write(int b) throws IOException
for(int b=65; b<90; b++) { //반복문
fos.write(b); //A~Z까지 출력
//fos.flush();
}
fos.close(); //스트림을 닫는다.
System.out.println("파일로 저장 성공");
}catch ( FileNotFoundException fe) { 해당 위치에 파일이 없을때 에러
System.out.println(fe.getMessage());
}catch ( IOException fi) { 출력
System.out.println(fi.getMessage());
}
FileInputStream : 파일에서 1바이트 단위로 데이터를 읽어오기 위한 스트림클래스
try{
FileInputStream fis = new FileInputStream(""c:\\java\\abc.txt"");//저장한 위치
while(true){ 루프
int n = fis.read(); FileInputStream에서 읽어온 데이터를 read에 저장
if(n==-1); 더이상 읽을 대상이 없으면 -1을 리턴한다.
System.out.println((char)n); 문자로 출력하기 위해 강제형변환
}
fis.close(); 스트림 닫음
} catch(IOException ie){
System.out.prinln(ie.getMessage());
} catch(FileNotFoundException fe){
System.out.println("파일을 불러올수 없음"+fe.getMessage());
}
만약 저장위치에 경로를 적어주지 않으면 프로젝트내에 저장된다.