본문 바로가기
Java

예외 Exception

by leko 2023. 7. 13.

int num =Integer.valueOf(str);

 

String str = Integer.toString(num);

String str2 = Double.toString(num);

 

String str = String.valueOf(num);

 

int num = Integer.parseInt(str);

 

 

 

nextLine()  hello\n

nextInt()  hello

next()   hello

컴파일 에러(오류) : 문법에 맞지 않아 컴파일할 때 발견 

런타임 에러 : 실행시 발견하는 에러
자바에서는 실행시 발견하는 오류(Exception 과 error) 를 클래스로 정의 


Object
Throwable
미약 오류 Exception(RuntimeException IOException)                                              심각 오류     Error(OutOfMemoryError)

Exception과 그자손들(IOException , ClassNotFoundException)
: 사용자의 실수같은 외적요인으로인한예외

RuntimeException과 그 자손들

(ArithmeticException ClassCastException NullPointerException IndexOutOfBoundsException)
: 프로그래머의 실수로 발생하는 예외



예외 처리하기 -> try catch문 , 던져진 예외객체를 catch해서 적절한 작업을 수행, 메시지출력, 재입력, 무시, 프로그램 종
try{System.out.println(0/0); System.out.println(7);}

catch(ArithmeticException e){System.out.println(3);}

System.out.println(4);

답 3 4

catch (Exception e)는 모든 예외를 처리할 수 있다 왜? 최고 조상이니까


try{System.out.println(args[0]); System.out.println(7);}

catch(ArithmeticException e){System.out.println(3);}

System.out.println(4);
답 : 비정상종료여서 아무것도 안뜸. 빨간줄이뜸 ArrayIndexOutOfBoundsException



printStackTrace() : 예외 발생 당시의 호출스택에 있던 메서드의 정보와
                               예외 메시지를 화면에 출력한다
getMessage() : 발생한 예외클래스의 인스턴스에 저장된 메시지를 얻을 수 있다.

멀티 catch블럭: 내용이 같은 catch블럭을 하나로 합친것//부모자식관계는 안된다


예외 발생시키기declare : 예외가 던져졌다, 자바가상기계가 예외를 감지하고 응용프로그램에게 예외 객체를 던짐

어떤 메소드는 실행중에 발생한 예외를 호출한 쪽에 던짐

왜냐하면 메소드 자체적으로 처리못하거나 호출한쪽에 예외 발생했음을 알리기위해

package Exception;

import java.util.Scanner;

public class Ex2 {
	
	//예외를 던지는 메소드
	public static int quotient(int dividend , int divisor) throws ArithmeticException {
		return dividend / divisor;//예외발생 다시 이 q메소드를 호출한 main메소드로 돌아감
		//q메소드 그 자체적으로 처리하지못하니까
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int dividend;
		int divisor;
		while(true) {

			System.out.println("나뉨수");
			dividend = sc.nextInt();
			System.out.print("나눗수를 입력");
			divisor = sc.nextInt();
			try{
				System.out.println(dividend +"를"+ divisor+ "나누면"+ quotient(dividend , divisor));
				break;
			}catch(ArithmeticException e) { // 오류잡았당
				System.out.println("오류당"); //오류당 출력
			}
			
		}
		
		sc.close();

	}

}

예외처리하는 방법 :
 1.직접처리 try-catch문 
 2.예외 떠넘기기 예외선언하기 

void method() throws Exception1, Exception2, Exception3, ExceptionN{
}



void method() throws Exception{ //모든 예외의 최고 조상
}

main-> method1-> method2 -> method1 -> main
계속 떠넘겨서 jvm이 method2method1main 으로 비정상 종료됨

static void method1() throws Exception{
method2();
}
static void method2() throws Exception{
throw new Exception();
}

package Exception;

import java.io.FileNotFoundException;
import java.io.FileReader;

public class Ex5 {

	public static void main(String[] args)      방법 2 throws FileNotFoundException{
		// TODO Auto-generated method stub

		방법 1 
        try {
			FileReader input = new FileReader("abc.txt");// checked exception FileNotFoundException
		}catch(FileNotFoundException e) {
			
		}
        
        
   
		
		FileReader input = new FileReader("abc.txt");

	}

}



1. 연산자 new를 이용해서 발생시키려는 예외 클래스의 객체를 만든다음
Exception e = new Exception ("고의");


 
2 키워드 throw를 이용해서 예외를 발생시킨다.
throw e; 





Exception 클래스와 그자손들(IOException , ClassNotFoundException)
: 사용자의 실수같은 외적요인으로인한예외
checked 예외 : 컴파일러가 예외처리여부를 체크(예외처리가 필수)
ex) throw new Exception(); 는 컴파일에러발생

RuntimeException 클래스와 그 자손들

(ArithmeticException ClassCastException형변환 NullPointerException참조변수가  null일때 IndexOutOfBoundsException 배열 벗어남)
: 프로그래머의 실수로 발생하는 예외
unchecked 예외 : 컴파일러가 예외처리여부를 체크 안함(예외처리가 선택)
ex) throw new RuntimeException(); 는 런타임에러발생


Throwable 클래스

java.lang 패키지에속함

모든 예외와 오류의 상위클래스

메시지 : 예외에 대한 구체적 설명

stack trace : 객체가 생성될 당시의 스택의 상태

기능

toString : 예외객체를 문자열로   java.lang.ArithmeticException: / by zero

getMessage : 예외 객체에 저장된 메시지 리턴 byZero

printStackTrace : 예외 객체에 저장된 stack trace 출력

getStackTrace : 예외 객체에 저장된 stack trace 리턴 , StackTraceElement[] 타입을 리턴

package Exception;

public class Ex6 {
	public static void main(String[] args) {
		f();
	}
	
	public static void f() {
		g();
	}
	public static void g() {
		try {
			int a = 100/0;
		}catch(ArithmeticException e) {
			StackTraceElement[] arr;
			arr = e.getStackTrace();
			e.printStackTrace(); //java.lang.ArithmeticException: / by zero g 13 f 9 main 5 
		
			for(StackTraceElement ele : arr) {
				System.out.printf("%s\t %s\t %s\t %d\n",
				ele.getClassName(),// Exception.Ex6
				ele.getFileName(), // Ex6.java
				ele.getMethodName(), // g
				ele.getLineNumber()); // 13
			
			}
		
		
		
		
		}
	}
}


Exception 클래스
java.lang 패키지에 속함

Throwable 클래스의 하위 클래스

package Exception;

public class Ex7 {
	public static void main(String[] args) {
		
		f();
		System.out.print("main");
		
	}
	public static void f() {
		Exception ex;
		ex = new Exception();
		ex.printStackTrace(); // java.lang.Exception at Exception.Ex7.f(Ex7.java:12) main 6
		
		
		ex = new Exception("test Exception"); 
		ex.printStackTrace(); // java.lang.Exception: test Exception f 16 main 6
		
		ex = new ArithmeticException ();
		ex.printStackTrace(); //java.lang.ArithmeticException f 19 main 6
		
		ex = new ArithmeticException("+-/*");
		ex.printStackTrace(); // java.lang.ArithmeticException: +-/* f 22 main 6
		
	}
}
package Exception;

public class Ex10 {
	public static void main(String[] args) {
		try {
			f();
		}catch(Exception e) {
			e.printStackTrace();//2. java.lang.Exception : g에서 예외 생성 at Exception.Ex10.g(Ex10.java.23)  f 16 main 6
		}
		System.out.println("메인함수당"); //3.
		
	}
	
	static void f() throws Exception {
		try{
			g();
		}catch(Exception e) {
			System.out.println("f에서 잡았당");//1.
			throw e;
		}
	}
	static void g() throws Exception{
		throw new Exception ("g에서 예외 생성");
	}
}
package Exception;
//StackUnwinding.java 
public class Ex11 {
	public static void main(String[] args) {
	try {
		f();
	}catch(Exception e) {
		Exception e3 = new Exception();
		System.out.println("메인함수당");  //5
		e3.printStackTrace();// 6 java.lang.Exception at Excepton.Ex11.main(Ex11.java:8)
	}
	
	
}

static void f() throws Exception {
	try{
		g();
	}catch(Exception e) {
		Exception e2 = new Exception();
		System.out.println("f함수당");  //3
		e2.printStackTrace(); //4 java.lang.Exception at Exception.Ex11.f(Ex11.java:20) main 6
		throw e2;
		
	}
}
static void g() throws Exception{
	Exception e = new Exception();
	System.out.println("g함수당"); //1.
	e.printStackTrace();//2. java.lang.Exception at Exception.Ex11.g(Ex11.java:28) f 18 main 6
	throw e;
}
}

Chained Exception 연결된 예외 객체

catch한 예외 객체를 새로운 예외객체에 연결하여 같이 던짐

새로운 예외객체를 받은 쪽은 이전에 발생한 예외를 확인할 수 있음

 

new Exception (이전 예외 객체)

new Exception (메시지, 이전 예외객체)

 

package Exception;

import java.io.IOException;
/*java.lang.Exception: hi
	at Exception.Ex12.f(Ex12.java:19)
	at Exception.Ex12.main(Ex12.java:8)
Caused by: java.io.IOException
	at Exception.Ex12.g(Ex12.java:25)
	at Exception.Ex12.f(Ex12.java:17)
	... 1 more
*/
public class Ex12 {
	public static void main(String[] args) {
		try {
			f();
		}catch(Exception ex) {
			System.out.println("main함수");
			ex.printStackTrace();//
		}
		
	}
	static void f() throws Exception {
		try {
			g();
		}catch(IOException e) {
			Exception e2 = new Exception("hi", e);  //이전예외객체e를 사용해 Exception e2객체생성
			throw e2;
		}
		
	}
	static void g() throws IOException{
		IOException e = new IOException();
		throw e;
	}
}
package Exception;

import java.util.Scanner;

public class Ex14 {

	private static int num;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		while(true) {
			try {
				int[] iArray = getInput();
				for (int i = 0; i < iArray.length; i++) {
					iArray[i] = i * 20;
				}
				for (int ele : iArray) {
					System.out.print(ele + "\t");
					
				}
				break;
			}catch (NegativeArraySizeException e) { //trycatch문에서 NegativeArraySize 예외 드디어 잡아 해당 예외 발생할경우 메시지 출력한다~!~!~!~!~!~
				System.out.println("배열의 크기가 음수입니다.");
				continue;
			}	
		}
		
	}

	public static int[] getInput() throws NumberFormatException {  //Number 예외 던지는 메소드
		Scanner sc = new Scanner(System.in);
		while (true) {
			System.out.println("배열 크기를 입력하세요:");
			String str = sc.next();
			try {
				num = Integer.parseInt(str);
				break;
			} catch (NumberFormatException e) { //try catch 자체적으로  예외 해결
				System.out.println("잘못된 형식의 숫자입니다.");
				continue;
			}
		}

		int[] result = makeArray(num);
		return result;
		//아까 NegativeArray~는 아직도 해결못한 예외이므로 main함수로 가자
	}

	public static int[] makeArray(int num) throws NegativeArraySizeException { //Negative 예외를 던지는 메소드
		int[] result = new int[0];
		if (num < 0) {
			throw new NegativeArraySizeException(); //예외 진짜 던짐 //자체적으로 해결못하니 이 함수호출한 getInput으로가자
		}
		result = new int[num];
		return result;
	}
}

'Java' 카테고리의 다른 글

Stream  (0) 2023.07.31
입출력 스트림과 파일 입출력  (0) 2023.07.13
12장 Collection FrameWork Generics  (0) 2023.07.10
object oriented programming 개념 정리  (0) 2023.07.08
11장 Collection FrameWork  (0) 2023.07.06