자바 예외처리
;
;
;
;
;예외처리 ;(Exception Handling)
예외 ;: ;문제발생 ;-프로그램비정상
예외처리 ;-정상종료
;
자바에서는 예외 클래스(API)제공
이런 클래스들을 사용해서 문제가 발생했을때 정상종료를 할 수 있게 한다.
;
1. try{실행문}catch(...Exception e){예외처리문}finally{무조건 실행(파일닫기나 ;DB연결종료 같은것들 잘쓰고 자원반납할 때 사용)}
;
1.코드에서 예외발생 ;->2.예외발생정보 ;->(자바JVM로) 3.예외클래스조회 ;4. ;객체생성 ;5.JVM에서다시 던진다 코드로 ;->코드에서 받아서 객체를 받아서 예외처리소스->정상종료
;
캐치문에서 실행문을 수정할수는 없고 어떠한 에러가 발생했는제 알려줌으로써 예외처리를함!
;
try{}finally{} //캐치없는거로 특정한 거를 강조하고싶을때 사용
;
;
;
2. throws (throw랑 혼동하지말기)
* try catch - > ;발생된 예외를 발생한 곳에서 처리
* throws -> ;발생된 예외를 ;(자신을 호출한 메소드로) ;떠넘기는방식
-main A()-> A() -> B()
-최종적으로 메인에서는 ;throws로 던지지말고 ;(가능은함) -> ;왠만하면 ;try catch문으로 잡기
throws로 예외를 던지는 이유는
;
우리가 명시적으로 예외발생 시켜주기
throws new ;예외클래스명();
;
사용자정의 예외클래스
1.extends Exception
2.(string ;가진)생성자 한 개
;
;
;
;------------------------------------------
;
;
public class ExceptionTest {
;
public static void main(String[] args) {
// TODO Auto-generated method stub
;
System.out.println("프로그램시작");
;
try {
;
int n=10/0;
System.out.println(n); //예외1 ;/by zero 출력
;
String name=null;
System.out.println(name.length());//예외2 ;null 출력
;
} catch (ArithmeticException e) { //Exception e도 가능 (다형성)
//e.printStackTrace();
System.out.println(e.getMessage());
}catch (NullPointerException e) { //try실행문에서 소스가 길어져서 예외가 여러개 발생할 가능성이 있을때 발생할 예외만큼의 다중catch문 작성.
System.out.println(e.getMessage());
}catch (Exception e) {//예외처리 최상위 클래스인 Exception은 마지막에 써주기. ;
System.out.println(e.getMessage());
}finally{
System.out.println("finally반드시실행");
}
System.out.println("프로그램정상종료");
;
try{
//...
}finally{
//반드시 수행될 문장
} ;
}
;
}
---------------------
;
;
;
;
;
;
class Exp{
public void a()throws Exception{
b();
}
//public void b() throws ArithmeticException,NullPointerException{ //throws로 자신을 부른곳으로 예외발생시 보냄 ;
public void b() ;throws Exception{ //Exception로도 가능하지만 권장하지는 않음 / 자세하게 위처럼 써주는것을 권장 ;
int n= 10/1;
String name =null;
System.out.print(name.length());
}
}
;
;
public class ExceptionText2 {
;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("프로그램시작");
Exp e = new Exp();
try{
e.a(); ;// null
}catch(ArithmeticException ex){
System.out.println(ex.getMessage());
}catch(NullPointerException ex){
System.out.println(ex.getMessage());
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println("프로그램 정상종료");
}// end main
;
}// class end
----------------------------------
;
사용자정의 예외클래스 .
;
public class ZeroException extends Exception {
;
;
;
;
public String ZeroException(String messege) {
// TODO Auto-generated constructor stub
super(messege);
}
;
;
;
}
----
import java.util.Random;
;
;
;
class Exp2{
; public void a() ;throws ZeroException ;{
; ;//난수 발생
; ;Random r = new Random();
; ;int n = r.nextInt(3); // 0 , 1 , 2 ,3 난수발생
; ;
;//사용자가 지정한 특별한 조건 (ex 0이면 예외)
; ;System.out.println("n : "+n); ;
; ;
; ;if(n==0){//강제적으로 예외 발생 ; 0나오면 예외처리하고 출력안됨 위에서 ;
; ;throw new ZeroException();
; ;}
; ;}
}//class end
;
;
public class ExceptionTest3 {
;
public static void main(String[] args) {
;
System.out.println("프로그램시작");
;
Exp2 e2= new Exp2();
try{
e2.a();
}catch(ZeroException e){
System.out.println(e.getMessage());
}
;
System.out.println("프로그램 정상종료");
;
}//end mian
;
}//end class
;
;---------
;
;
;
class AAA{
;public void a() ;throws ZeroException{
; ;
;//1. 시스템이 발생시킨 예외를 try cahtck한다.
;
;try{
;int n= 10/0;//시스템이 예외 발생시킴
;}catch(ArithmeticException e){
;//2.사용자 예외클래스를 다시 발생
;throw new ZeroException("0으로 나누어 에러 발생");
;}
;}
;
}
;
public class ExceptionTest4 {
;
public static void main(String[] args) {
// TODO Auto-generated method stub
;
System.out.println("프로그램시작");
;
AAA a= new AAA();
;
try{a.a();
}catch(ZeroException e){
System.out.println(e.getMessage());
}
;
System.out.println("프로그램 정상종료");
}
;
}
---------------
확대 축소 오버라이딩
;
import java.io.IOException;
;
//오버라이딩
;
class Parent{
public void a() throws ArithmeticException{}
public void b(){}
public void c()throws Exception{}
}
;
class Child extends Parent{
public void a(){} //throws 축소만 가능 ;
//public void b() throws IOException{} // 확대 불가
public void c() throws IOException{} //축소 가능
;
}
;
public class ExceptionTest5 {
;
public static void main(String[] args) {
// TODO Auto-generated method stub
;
}
;
}
;
------------------------------------------------
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.Buffer;
;
;
;
public class ExceptionTest6 {
;
public static void main(String[] args) {
// TODO Auto-generated method stub
;
//파일읽기 ==>IO발생
// C:\aa.txt
//파일정보 알려주기
File f = new File("C:\\aa.txt");
BufferedReader buffer = null; //try에서 빼주기 (finally에서 ;buffer 사용할수 있게)
//파일에서 읽기
//컴파일 checked 예외 ; (실행시간에 발생하는 런타임에러랑 반대)
try {
FileReader reader = new FileReader(f);
//읽어들임
buffer = new BufferedReader(reader);
String data= buffer.readLine();//핝줄씩 읽기
while(data!=null){ //null = 파일 끝 EOF
System.out.println(data);
data= buffer.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(buffer !=null)
buffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
;
}
;