반응형
예외처리(Exception) |
|
Exception클래스 : 예외처리의 최고 조상 클래스(자료형) | |
- 예측가능한 에러를 정상종료가 되도록 처리하는 방법 방법 1. 책임감이 강한형 : try ~ catch문 (반드시 같이 존재) : try문에서 발생된 에러는 catch문에서 해결함. : 내가 발생시킨 에러를 내가 처리함. - try문 : 해당 실행문들을 감싸는 위치에 존재 - catch문 : try문에서 발생되는 에러를 처리하는 명령문을 감싸는 위치에 존재함 |
try { 실행코드들; ...; } catch (예외처리자료형명 객체명) { //try문에서 에러가 발생될 경우 처리할 실행코드들; ...; } [ finally { 에러발생여부 상관없이 반드시 try ~ catch문이 실행된 후 마지막에 실행되는 부분의 코드들을 기술; } ] |
2. 책임전가형 : throws : 메소드를 호출한 곳에서 에러를 처리하도록 책임을 전가함. : 위치 메소드 선언문의 ()소괄호 뒤에 존재함. 책임전가받은 Exception은 throws Exception 이상이여야 한다. |
[접근제어자][기타제어자] 리턴타입 메소드명([매개변수들...]) throws 예외처리자료형명, ... { 실행코드들...; } |
Exception | ||
ArrayIndexOutOfBoundsException | 배열의 범위 오류 시 | 배열 2개 입력해야하는데 1개값만 입력시 |
ArithmeticException | 산술연산에러 시 | 젯수가 0 인 경우 |
NumberFormatException | 숫자값이 아닌 다른 자료형이 들어오는 경우 에러 | 5 자 |
ExceptEx00.java
try ~ catch
throws
package exceptex; public class ExceptEx00 { //try ~ catch public static void main(String[] args) { try { System.out.println("1111"); Class c = Class.forName("String"); //"java.lang.String" //에러시점 이후부터는 중괄호 밖으로 나감 System.out.println("1111"); System.out.println(c); } catch (Exception e) { // } catch (ClassNotFoundExcetion e) { System.out.println(e); } System.out.println("시스템 정상 종료"); }
1111 java.lang.ClassNotFoundException: String 시스템 정상 종료
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException { System.out.println("1111"); Class c1 = Class.forName("String"); //에러시점 이후부터는 중괄호 밖으로 나감 System.out.println(c1); System.out.println("2222"); }
1111 Exception in thread "main" java.lang.ClassNotFoundException: String at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) at java.base/java.lang.Class.forName0(Native Method) at java.base/java.lang.Class.forName(Class.java:315) at exceptex.ExceptEx00.main(ExceptEx00.java:23)
ExceptEx01.java
package exceptex; public class ExceptEx01 { public static void main(String[] args) { int c; //지역변수 자동초기화값 없음 System.out.println("1111"); // c = 4 / 0; System.out.println("2222"); try { System.out.println("3333"); c = 4 / 0; //젯수가 0이면 에러발생 System.out.println("4444"); } catch(ArithmeticException e) { // } catch(Exception e) { //해당 에러처리 코드를 모르면 최고조상으로 기술가능 System.out.println("젯수(나누는 수)는 0이 될 수 없습니다.\n0이상이 되도록 변경해주세요."); } System.out.println("5555"); System.out.println("시스템 종료"); } }
1111 2222 3333 젯수(나누는 수)는 0이 될 수 없습니다. 0이상이 되도록 변경해주세요. 5555 시스템 종료
ExceptEx02.java
package exceptex; public class ExceptEx02 { public static void main(String[] args) { System.out.println(1); System.out.println(2); try { System.out.println(3); System.out.println(0 / 0); //0으로 나눈값이 에러 catch문으로 넘어감 System.out.println(4); //실행되지 않는다. } catch (ArithmeticException ae) { System.out.println(ae); System.out.println("ArithmeticException에러메세지 : " + ae.getMessage()); } } }
1 2 3 java.lang.ArithmeticException: / by zero ArithmeticException에러메세지 : / by zero
ExceptEx03.java
package exceptex; public class ExceptEx03 { public static void main(String[] args) { String c = null; //주소값을 할당받지 못 한 상태 // System.out.println(" 문자열 값은 : " + c.toString()); System.out.println(" 문자열 값은 : " + c); try { System.out.println(" 문자열 값은 : " + c.toString()); //null값으로 문제되지는 않으나. 해당 주소값을 통한 실행문이 기술되어 오류발생 } catch (NullPointerException e) { //NullPointerException 주소값이 없는 것에 대한 에러 System.out.println("예외가 발생하여 Exception 객체가 잡음"); System.out.println(e); //해당 Exception 코드 출력 System.out.println(e.getMessage()); //에러메세지 System.out.println(e.getCause()); //에러원인 } finally { //finally 무조건 실행됨 System.out.println("finally 블럭 수행"); } System.out.println("정상 종료"); } }
문자열 값은 : null 예외가 발생하여 Exception 객체가 잡음 java.lang.NullPointerException null null finally 블럭 수행 정상 종료
ExceptEx04.java
ArrayIndexOutOfBoundsException
ArithmeticException
NumberFormatExceptionpackage exceptex; public class ExceptEx04 { public static void main(String[] args) { //args란 이름을 가진 String 배열 try { // 해보기 : // 매개인자 1개 입력하고 실행하기 : 숫자로 // 매개인자 2개 입력하고 실행하기 : 숫자로, 젯수 0으로 입력하기 // 매개인자 String로 입력하고 실행하기 System.out.println("매개변수로 받은 두 개의 값"); int a = Integer.parseInt(args[0]); //Integer문자열 값을 parseInt정수로 변환 //args[0] 0번 인덱스값 System.out.println("a의 값: " + a ); int b = Integer.parseInt(args[1]); System.out.println("b의 값: " + b); System.out.println(" a = " + a + ", b = " + b); System.out.println(" a를 b로 나눈 몫 = " + (a / b)); System.out.println("나눗셈 수행"); } catch (ArithmeticException e) { //산술연산에러 시 System.out.println("================================="); System.out.println("ArithmeticException 처리 루틴 : "); System.out.println(e + "예외 발생"); } catch (ArrayIndexOutOfBoundsException e) { //배열의 범위 오류 시 System.out.println("================================="); System.out.println("ArrayIndexOutOfBoundsException 처리 루틴 : "); System.out.println(e + "예외 발생"); } catch (NumberFormatException e) { //숫자값이 아닌 다른 자료형이 들어오는 경우 에러 System.out.println("================================="); System.out.println("NumberFormatException 처리 루틴 : "); System.out.println(e + "예외 발생"); } catch (Exception e) { //자바의 전체 에러 범위 처리 시 //Exception 최고조상 기술문은 가장 마지막에 기술되어야 한다. //그 이하 Exception들은 동급으로 순서 상관없이 기술 가능. System.out.println("Exception 관련 모든 예외 처리 루틴 : "); System.out.println(e + " 예외 발생"); } finally { System.out.println("================================="); System.out.println("finally 블럭 수행"); } } }
ExceptEx05.javapackage exceptex; public class ExceptEx05 { public static void main(String[] args) { try { // 해보기 : // 매개인자 1개 입력하고 실행하기 : 숫자로 // 매개인자 2개 입력하고 실행하기 : 숫자로, 젯수 0으로 입력하기 // 매개인자 String로 입력하고 실행하기 System.out.println("매개변수로 받은 두 개의 값"); int a = Integer.parseInt(args[0]); //Integer문자열 값을 parseInt정수로 변환 //args[0] 0번 인덱스값 System.out.println("a의 값: " + a ); int b = Integer.parseInt(args[1]); System.out.println("b의 값: " + b); System.out.println(" a = " + a + ", b = " + b); System.out.println(" a를 b로 나눈 몫 = " + (a / b)); System.out.println("나눗셈 수행"); } catch (Exception e) { System.out.println("================================="); System.out.println("Exception 관련 모든 예외 처리 루틴 : "); System.out.println(e + " 예외 발생"); } finally { System.out.println("================================="); System.out.println("finally 블럭 수행"); } } }
ExceptEx04.java ExceptEx05.java
Exception 단독기술로 실행시5 //배열의 범위 오류 시 매개변수로 받은 두 개의 값
a의 값: 5
=================================
ArrayIndexOutOfBoundsException 처리 루틴 :
java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1예외 발생
=================================
finally 블럭 수행매개변수로 받은 두 개의 값
=================================
Exception 관련 모든 예외 처리 루틴 :
java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 예외 발생
=================================
finally 블럭 수행5 0 //산술연산에러 시 매개변수로 받은 두 개의 값
a의 값: 5
b의 값: 0
a = 5, b = 0
=================================
ArithmeticException 처리 루틴 :
java.lang.ArithmeticException: / by zero예외 발생
=================================
finally 블럭 수행매개변수로 받은 두 개의 값
a의 값: 5
b의 값: 0
a = 5, b = 0
=================================
Exception 관련 모든 예외 처리 루틴 :
java.lang.ArithmeticException: / by zero 예외 발생
=================================
finally 블럭 수행5 자 //숫자값이 아닌 다른 자료형이 들어오는 경우 에러 매개변수로 받은 두 개의 값
a의 값: 5
=================================
NumberFormatException 처리 루틴 :
java.lang.NumberFormatException: For input string: "자"예외 발생
=================================
finally 블럭 수행매개변수로 받은 두 개의 값
a의 값: 5
=================================
Exception 관련 모든 예외 처리 루틴 :
java.lang.NumberFormatException: For input string: "자" 예외 발생
=================================
finally 블럭 수행
ExceptEx06.java
stack
package exceptex; public class ExceptEx06 { public static void main(String[] args) { try { String c = null; System.out.println("c값 : " + c); System.out.println(" 문자열 값 : " + c.toString()); //null값으로 문제되지는 않으나. 해당 주소값을 통한 실행문이 기술되어 오류발생 System.out.println("c값 : " + c); } catch (Exception e) { System.out.println(" >> 예외처리 구문 << "); System.out.println(" >> e << "); System.out.println(e); System.out.println(" >> e.toString() << "); System.out.println(e.toString()); System.out.println(" >> e.getMessage() << "); System.out.println(e.getMessage()); // 발생한 예외 클래스의 인스턴스에 저장된 메세지 얻어오기 System.out.println(" >> e.printStackTrace() << "); e.printStackTrace(); //예외 발생 당시의 호출 stack에 있는 메소드의 정보와 예외 메세지를 화면에 출력 } finally { System.out.println("finally처리"); } System.out.println("완료"); } }
c값 : null >> 예외처리 구문 << >> e << java.lang.NullPointerException >> e.toString() << java.lang.NullPointerException >> e.getMessage() << null >> e.printStackTrace() << java.lang.NullPointerException at exceptex.ExceptEx06.main(ExceptEx06.java:9) finally처리 완료
ExceptEx07.java
package exceptex; public class ExceptEx07 { public static void main(String[] args) { try { System.out.println("1111"); method1(); System.out.println("2222"); } catch (NumberFormatException e) { System.out.println("main 에서 NumberFormatException예외 처리"); System.out.println(e.getMessage()); } catch (Exception e) { System.out.println("main 에서 예외 처리"); System.out.println(e.getMessage()); // e.printStackTrace(); } System.out.println("종료"); } static void method1() throws Exception { //책임전가받은 Exception은 throws Exception 이상이여야 한다. //호출한 try문에 책임전가 System.out.println("예외발생시키기"); // throw new Exception(); //throw키워드 - 예외를 고의로 발생시킴 //매개변수가 없을시 null값 출력 throw new Exception("숫자형식이 아닙니다."); } // static void method1() throws Exception { // System.out.println("예외발생시키기"); // try { // throw new Exception(); //예외를 고의로 발생시킴 // } catch (Exception e) { // e.printStackTrace(); // } }
1111 예외발생시키기 main 에서 예외 처리 숫자형식이 아닙니다. 종료
ExceptEx08.java
package exceptex; public class ExceptEx08 { public static void main(String[] args) { try { findClass(); } catch (Exception e) { //ClassNotFoundException 이상 처리가 되어야 한다. System.out.println("클래스가 존재하지 않습니다."); System.out.println("에러 사유: " + e); } } public static void findClass() throws ClassNotFoundException { Class clazz = Class.forName("java.lang.WowClass"); //forName 책임을 질 실행문이 필요함 } }
클래스가 존재하지 않습니다. 에러 사유: java.lang.ClassNotFoundException: java.lang.WowClass
스트림(Stream) |
입출력 라이브러리는 java.io패키지에서 제공됨. 스트림 : 단방향으로 흐르는 데이터의 흐름 바이트 스트림 : 그림, 멀티미디어, 문자 등 모든 종류의 데이터를 입출력할 때 사용 문자 스트림 : 문자만 입출력할 때 사용 바이트 스트림의 최상위 클래스 : InputStream, OutputStream 하위 클래스 : 예) FileInputStream, FileOutputStream 문자 스트림 최상위 클래스 : Reader, Writer 하위 클래스 : 예) FileReader, FileWriter |
Buffered 일시적으로 공간을 늘려 누적 후 실행 |
바이트 스트림 | 문자 스트림 | ||
InputStream | OutputStream | Reader (입력) | Writer (출력) |
FileInputStream | FileOutputStream | FileReader | FileWriter |
bufWriter = new BufferedWriter (new OutputStreamWriter(socket.getOutputStream())); |
||
FileWriter | OutputStreamWriter | FileOutputStream |
: 문자열이나 char[]배열로 값입력시 FileReader 객체를 통해 바로 읽어 들일 수 있다. FileWriter로 입력을 하더라도 byte코드 한 개 한 개 입력하여 작성하는 경우는 반드시 byte코드를 문자 스트림방식으로 변환해서 읽어야만 한다. |
바이트 코드로 파일을 생성할 수 있다. |
bufReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); | ||
FileReader | InputStreamReader | FileInputStream |
바이트 코드로 파일을 읽어 들일 수 있다. 바로 문자로 출력이 어렵기 때문에 InputStreamReader를 통해 문자스트림형식으로 변환 후 출력가능하다. FileOutputStream을 이용해서 파일을 작성할 때 인코딩을 설정하여 작성하는 경우 반드시 File을 읽어들일 때도 인코딩을 설정해서 읽어주어야 한다. |
FileEx01_00.java
package fileex; import java.io.FileWriter; public class FileEx01_00 { public static void main(String[] args) throws Exception { String source = " 죽는 날까지 하늘을 우러러 한 점 부끄러움이 없기를\n" + "잎새에 이는 바람에도 나는 괴로워했다.\n" + "별을 노래하는 마음으로 모든 죽어가는 것을 사랑해야지.\n" + "오늘 밤에도 별이 바람에 스치운다.\n"; System.out.println(source.length()); char intxt[] = new char[source.length()];//문자갯수만큼의 배열형성 //getChars(복사할 객체의 시작인덱스번호(int), 복사할객체의 마지막인덱스-1(int), //복사해서 붙여넣기할 객체명, 붙여넣을 객체의 시작 위치 인덱스 번호(int); source.getChars(0, source.length(), intxt, 0); // 0~ 마지막인덱스번호까지(칸수-1) // source.getChars(6, 20, intxt, 5); // 지 하늘을 우러러 한 점 //FileWriter 문자전용 생성 FileWriter fw = new FileWriter("data1.txt"); //파일생성 //C:\jwork\lastprj\data1.txt fw.write(intxt); //.write()파일내용입력 // fw.write(source); fw.close(); //반드시 닫아주는 메소드 존재해야 마무리됨. 미기술시 메모리 소비됨 } }
103
C:\jwork\lastprj\data1.txt source.getChars(6, 20, intxt, 5);
fw.write(intxt);
fw.close();지 하늘을 우러러 한 점 source.getChars(0, source.length(), intxt, 0);
fw.write(intxt);
or fw.write(source);
fw.close();죽는 날까지 하늘을 우러러 한 점 부끄러움이 없기를
잎새에 이는 바람에도 나는 괴로워했다.
별을 노래하는 마음으로 모든 죽어가는 것을 사랑해야지.
오늘 밤에도 별이 바람에 스치운다.
FileEx01_01.java
package fileex; import java.io.*; public class FileEx01_01 { public static void main(String[] args) throws IOException { String path = "c:/upload/files"; File file = new File(path); //File(경로) 없는 경로도 그대로 받아들임. if(!file.isDirectory()) {file.mkdirs();} //file.mkdir 폴더 한 단계까지만 c:/upload //file.mkdirs 중첩된 폴더 c:/upload/files if(!file.exists()) {file.mkdirs();} //.exists() 요청한 파일뿐만 아니라 폴더까지 path = path+ "/file.txt"; //c:/upload/files/file.txt //String path데이터 변경으로 주소값이 바뀜 // FileWriter("파일경로포함/파일명.확장자명", append여부에 대한 boolean값); //true는 실행시 파일내용 뒷 줄에 추가 됨. //디폴트는 false임. false는 덮어쓰기 됨. FileWriter fw = new FileWriter(path, true); //매개변수가 한 개인 경우 무조건 덮어쓰기 됨. fw.write("FileWriter는 한글로된 " + "\n"); fw.write("문자열을 바로 출력할 수 있다." + "\n"); // fw.flush(); //임시적으로 저장해놓았다가 출력함 fw.close(); //fw.flush();자동실행기능 탑재 System.out.println("파일에 저장되었습니다."); } }
파일에 저장되었습니다.
FileWriter는 한글로된
문자열을 바로 출력할 수 있다.
FileEx01_02.java
FileWriter
FileReader
package fileex; import java.io.*; public class FileEx01_02 { public static void main(String[] args) throws IOException { // \r : 캐리지리턴, 그 줄의 처음으로 이동하라는 의미 // \n : 한 줄 바꿈의 의미 // \r\n : 개행문자, 다음 줄의 처음으로 이동하라는 의미 String currDir = System.getProperty("user.dir"); //()에 해당되는 속성을 가져오삼 System.out.println(currDir); File file = new File(currDir+"/test.txt"); if (!file.exists()) file.createNewFile(); //file생성 FileWriter fw = new FileWriter(file); //true는 실행시 파일내용 뒷 줄에 추가 됨. //디폴트는 false임. false는 덮어쓰기 됨. char[] buf = { 'm', 'e', 's','s','a','g','e'}; for (int i = 0; i < buf.length; i++) fw.write(buf[i]); fw.write("이 줄의 마지막에서 개행문자 \r\n"); fw.close(); FileReader fr = new FileReader(file); final int EOF = -1; //EndOfFile int c ; while ((c = fr.read()) !=EOF) { //read() 유니코드값 //!EOF -1, 없는 값이 나올때까지 // System.out.println(c + ", "); //유니코드값 출력 System.out.print((char)c); } fr.close(); } }
C:\jwork\lastprj message이 줄의 마지막에서 개행문자
FileEx02.java
FileReader
package fileex; import java.io.FileReader; public class FileEx02 { public static void main(String[] args) throws Exception { FileReader fr = new FileReader("data1.txt"); //c:/jwork/lastprj/data1.txt int i; while ((i = fr.read()) != -1) { System.out.print((char) i); } fr.close(); } }
죽는 날까지 하늘을 우러러 한 점 부끄러움이 없기를 잎새에 이는 바람에도 나는 괴로워했다. 별을 노래하는 마음으로 모든 죽어가는 것을 사랑해야지. 오늘 밤에도 별이 바람에 스치운다.
FileEx03.java
package fileex; import java.io.*; public class FileEx03 { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("stream1.txt"); //바이트(숫자형) 스트림 파일을 출력하기 위한 객체 fos생성 //'/' = '\\'경로 //FileReader/ Writer는 문자열 입력 //Stream은 //fis.write for (int i = 0; i <5; i++) { fos.write(i); } fos.close(); System.out.println("ByteStreamFile을 생성"); FileWriter fw = new FileWriter("data1.txt"); for (int i = 69; i <80; i++) { fw.write(i); ///숫자 // String s = i+""; // fw.write(s); } fw.close(); System.out.println("FileWriter을 생성"); FileReader fd = new FileReader("data1.txt"); int c ; while((c = fd.read()) != -1) { System.out.println(c); // System.out.println((char)c); ///문자로 출력 } fw.close(); // FileInputStream fis = new FileInputStream("stream1.txt"); FileInputStream fis = new FileInputStream("data1.txt"); //바이트 스트림 입력을 위한 객체 fis 생성 int i; while((i = fis.read()) != -1) { // System.out.println(i); System.out.println((char)i); } System.out.println("ByteStream을 File로부터 입력"); fis.close(); } }
ByteStreamFile을 생성 FileWriter을 생성 69 70 71 72 73 74 75 76 77 78 79 E F G H I J K L M N O ByteStream을 File로부터 입력
0
1
2
3
4
5
FileEx03_01.java
package fileex; import java.io.*; public class FileEx03_01 { public static void main(String[] args) { try { OutputStream output = new FileOutputStream("C:/jwork/Output.txt");//내용이없는 공파일이 만들어짐 String str = "오늘 날씨는 아주 덥습니다."; byte[] by = str.getBytes(); //Stream으로된 자료형들은 문자열로 바로 사용불가하므로 byte개열화 output.write(by); //bye오버라이드된 방식이 output.close(); FileInputStream fis = new FileInputStream("C:/jwork/Output.txt"); InputStreamReader isr = new InputStreamReader(fis); int c; while ((c=isr.read()) !=-1) { System.out.print((char)c); } isr.close(); fis.close(); System.out.println(); System.out.println("작업 완료\n"); } catch (Exception e) { e.getStackTrace(); } } }
오늘 날씨는 아주 덥습니다. 오늘 날씨는 아주 덥습니다. 작업 완료
package fileex; import java.io.*; public class FileEx03_02 { public static void main(String[] args) throws IOException { //파일 출력용 FileOutputStream fos1 = new FileOutputStream("c:/jwork/out_utf8.txt", true);//append사용(추가해서 사용) FileOutputStream fos2 = new FileOutputStream("c:/jwork/out_ansi.csv");//덮어쓰기 //ANSI계열 인코딩 유형 - ms949 : 확장완성형 //한글 깨짐의 보완하려면 ms949를 사용하는 것이 좋다. OutputStreamWriter osw1 = new OutputStreamWriter(fos1, "utf-8"); OutputStreamWriter osw2 = new OutputStreamWriter(fos2, "ms949");//ms문자표 int c; System.out.println("아무 내용이나 입력하세요. 꼭 엔터를 해 주어야만 글이 입력됩니다. \n종료를 원하시면 ctrl+z를 눌러주세요"); InputStreamReader isr = new InputStreamReader(System.in); while ((c = isr.read()) !=-1) { osw1.write(c); osw2.write(c); } System.out.println("작업 완료\n"); //닫을 때는 꼭 역순으로 닫아준다. isr.close(); osw1.close(); osw2.close(); fos1.close(); fos2.close(); FileInputStream fis = new FileInputStream("c:/jwork/out_ansi.csv"); isr = new InputStreamReader(fis, "ms949"); c = 0; while ((c=isr.read())!=-1) { System.out.print((char)c); } System.out.println(); System.out.println("출력 끝"); isr.close(); fis.close(); } }
아무 내용이나 입력하세요. 꼭 엔터를 해 주어야만 글이 입력됩니다. 종료를 원하시면 ctrl+z를 눌러주세요 하늘 바람 하하하 작업 완료 하늘 바람 하하하 출력 끝
반응형
'[JAVA]' 카테고리의 다른 글
[21일차] (0) | 2024.01.10 |
---|---|
[20일차] PrintWriter Thread synchronized Join Network (0) | 2024.01.09 |
[18일차] HashMap Hashtable Anonymous InnerClass InstanceInner StaticInner Local Ramda (0) | 2024.01.05 |
[17일차] Generic Wildcard Collection Framework (0) | 2024.01.04 |
[16일차 오후] 초기화블록 Generic Type (0) | 2024.01.03 |