4. 예외 처리 Exception handling
: 코드로 발생할수있는 에러를 미리 진단하고, 해결방안을 처리해 놓는것.
- 컴파일 에러 : 컴파일할때 발생(실행조차X) : 문법 오류 등
- 런터임 에러 : 실행하다 발생 : 문법적으로는 맞아 컴파일은 되는데 실행하다 발생
1) 예외는 메서드에서 처리.
2) try-catch 구문 (****api쓰면서 정말 많이 쓸꺼다*****)
try {
// 예외가 발생할것 같은 코드들....
}catch(NullPointerException e) {
// 예외 발생하면 대처해야할 코드들....
}catch(ArrayIndexOutOfBounds e) {
// 예외 발생하면 대처해야할 코드들....
}catch(Exception e) {
// 예외 발생하면 대처해야할 코드들....
}
3) 대표적인 예외
ArrayIndexOutOfBoundsException : 배열 인덱스번호 잘못 쓰면
ArithmeticException : 0으로 나눌려고 할때
NullPointerException : 객체 생성안하고 내용물 사용하려고 할때
NumberFormatException : 문자열이 나타내는 숫자와 일치하지 않는 타입의 숫자로 변환시 발생
ClassCastException : 클래스 형변환 에러
ClassNotFoundException : 찾는 클래스가 없을 경우
IOException : 입출력 동작 실패 또는 인터럽트 시 발생
IllegarArgumentException : 인자 전달 실패시
4) finally
예외 발생 여부와 상관없이 무조건 실행되는 블럭
메서드안에서 return을 만나도 finally 블럭이 있으면
실행하고 return됨.
try {
// 예외가 발생할것 같은 코드들....
}catch(Exception e) {
// 예외 발생하면 대처해야할 코드들....
}finally {
// 예외 발생 여부 상관없이 무조건 실행되야하는 코드들.....
}
5) 예외 발생시키는 키워드
throw 예외객체;
Exception e = new Exception();
throw e; // 예외 발생이야~~~~~~~~
package day14;
public class ClassEx34 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/* int number = 100;
int result = 0;
//for문을 안으로 넣어도 되고
try {result = number / (int)(Math.random()*10);
* for(int i = 0;i < 10; i++) {
System.out.println(result);
}catch(Exception e) {
System.out.println("0 발생");
}
*
*
*/ //
int number = 100;
int result = 0;
// 밖으로 빼도되고 단 결과는 다르다
for(int i = 0;i < 10; i++) {
try {result = number / (int)(Math.random()*10);
System.out.println(result);
}catch(Exception e) {
System.out.println("0 발생");
}
}
}
}
package day14;
import java.util.Scanner;
public class ClassEx35 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("3줄 입력");
String s1 = sc.next();
String s2 = sc.next();
String s3 = sc.next();
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
sc.nextLine();
System.out.println("주소를 입력");
String addr = sc.nextLine();
System.out.println(addr);
System.out.println("종료");
sc.close();
}
}
package day14;
public class ClassEx36 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(1);
try {
System.out.println(2);
System.out.println(0/0);
System.out.println(3); //건너뜀
}catch(Exception e) {
System.out.println(4);
}finally {
System.out.println(5);
}
System.out.println(6);
}
}
package day14;
public class ClassEx37 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println("hello");
throw new Exception("고의로 발생"); // 의도적 예외를 발생시켜서
//System.out.println("java"); //밑에 이줄은 출력안돼~!
}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace(); // 빨간줄 일부러 보여주는
System.out.println("Exception 발생");
}
}
}
package day14;
public class ClassEx38 {
//예외 발생하는것 부른쪽으로 토스
static void add() throws Exception {
System.out.println("add 실행");
throw new Exception();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//add();
}
}
package day14;
public class ClassEx39 {
static void method1() throws Exception {
method2();
}
static void method2() throws Exception {
throw new Exception();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
method1();
}catch(Exception e) {
System.out.println("처리할께");
e.printStackTrace();
}
}
}
package day14;
public class ClassEx40 {
static void method1() throws Exception {
try {
throw new Exception();
}catch(Exception e) {
System.out.println("method1 예외처리!!!");
throw e; // 또 문제를 만들어냄 !
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
method1();
}catch (Exception e) {
System.out.println("main 에서도 잡기");
}
}
}