예외가 발생하면 완벽하게 복구를 할 수가 없는 경우가 있다.
예외
- 프로그램이 실행되는동안 발생할수 있는 비정상적인 상태
- 컴파일시의 에러말고 실행시의 에러
- 모든 예외 => Exception을 사용
- 예외에는 구체적 예외, 일반적 예외가 있슴
- 처음에 구체적 예외로 거르다가
- catch문 밑으로 갈 수록 일반적 예외를 사용해라
- 마지막엔 Excpetion 써라
ArithmeticException 예외 발생
package com.javaex.exception;
import java.util.*;
public class ExceptionEx {
public static void main(String[] args) {
ArithmeticEx();
}
// 어떤 수를 0으로 나눌 때
private static void ArithmeticEx() {
double result = 0;
int num;
Scanner scanner = new Scanner(System.in);
System.out.print("정수 입력:");
// 예외 발생 가능 영역
num = scanner.nextInt();
result = 100/num;
System.out.println(result);
scanner.close();
}
}
ArithmeticException 예외 처리 ->
package com.javaex.exception;
import java.util.*;
public class ExceptionEx {
public static void main(String[] args) {
ArithmeticEx();
}
// 어떤 수를 0으로 나눌 때
private static void ArithmeticEx() {
double result = 0;
int num;
Scanner scanner = new Scanner(System.in);
System.out.print("정수 입력:");
try {
// 예외 발생 가능 영역
num = scanner.nextInt();
result = 100/num;
}catch(ArithmeticException e) {
System.err.println("0으로는 나눌 수 없어요");
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println(result);
scanner.close();
}
}
결과
정수 입력:0
0으로는 나눌 수 없어요
0.0
예제
package com.javaex.exception;
import java.util.*;
public class ExceptionEx {
public static void main(String[] args) {
ArithmeticEx();
}
// 어떤 수를 0으로 나눌 때
private static void ArithmeticEx() {
double result = 0;
int num;
Scanner scanner = new Scanner(System.in);
System.out.print("정수 입력:");
try {
// 예외 발생 가능 영역
num = scanner.nextInt();
result = 100/num;
}catch(InputMismatchException e) { // 정수 입력 안 했을 경우
System.err.println("정수로 해주세요");
}
catch(ArithmeticException e) { // 0으로 나눴을 경우
System.err.println("0으로는 나눌 수 없어요");
}
catch(Exception e) { // 모든 예외 처리 가능
e.printStackTrace();
}finally {
System.out.println("예외 처리 종료");
// 예외 유무 관계 없이 가장 마지막에
// 자원 정리 작업에 많이 활용
}
System.out.println(result);
scanner.close();
}
}
강제 예외 발생
ExceptionEx.java
package com.javaex.exception;
import java.io.IOException;
import java.util.*;
public class ExceptionEx {
public static void main(String[] args) {
// ArithmeticEx();
throwExceptionEx();
}
private static void throwExceptionEx() {
ThrowsExcept except = new ThrowsExcept();
try {
except.executeException(); // 호출하는 메소드에서 처리 못 하면
}catch(IOException e) {
System.err.println(e.getMessage());
}
System.out.println("예외 처리 완료");
}
}
호출하는 메서드에서 처리를 못 하면 예외를 그냥 던져주는게 좋음
사용자 정의 예외 사용
ExceptionEx.java
package com.javaex.exception;
import java.io.IOException;
import java.util.*;
public class ExceptionEx {
public static void main(String[] args) {
// ArithmeticEx();
throwExceptionEx();
}
private static void throwExceptionEx() {
ThrowsExcept except = new ThrowsExcept();
try {
except.executeRuntimeException(); // 호출하는 메소드에서 처리 못 하면 던져 주는 게 좋다.
except.executeException();
}catch(RuntimeException e) {
System.err.println(e.getMessage());
}catch(IOException e) {
System.err.println(e.getMessage());
}
// 사용자 정의 예외 사용
try {
System.out.println(except.divide(100, 0));
}catch(CustomArithException e) {
System.err.println(e.getMessage());
// 예외 상황 확인
System.err.println("나누어지는 수 : " + e.getNum1());
System.err.println("나누는 수 : " + e.getNum2());
}
System.out.println("예외 처리 완료");
}
}
ThrowsException.java
package com.javaex.exception;
import java.io.IOException;
// 사용자 정의 예외 정의
class CustomArithException extends ArithmeticException{
// 예외 상황 필드
private int num1;
private int num2;
public CustomArithException(String message, int num1, int num2) {
super(message);
// 예외 상황 정보 저장
this.num1 = num1;
this.num2 = num2;
}
public void setNum1(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public int getNum1() {
return this.num1;
}
public int getNum2() {
return this.num2;
}
}
public class ThrowsExcept {
// checked Exception
public void executeException() throws IOException {
System.out.println("강제 예외 발생");
throw new IOException("강제 예외");
}
//Unchecked Exception
public void executeRuntimeException() {
System.out.println("런타임오류");
throw new RuntimeException("런타임 예외");
}
//
public double divide(int num1, int num2) {
if(num2 == 0) {
//ArithmeticException
// 구체적 예외롤 전환하여 throw 하는 것이
// 1. 가독성을 높이고
// 2. 예외 상황 정보를 가져올 수 있다.
throw new CustomArithException("사용자 정의 예외", num1, num2);
}
return num1 / num2;
}
}
결과
런타임오류
런타임 예외
사용자 정의 예외
나누어지는 수 : 100
나누는 수 : 0
예외 처리 완료
'study > JAVA 전문가' 카테고리의 다른 글
얕은 복제, 깊은 복제 (0) | 2021.12.07 |
---|---|
인터페이스 (0) | 2021.12.07 |
추상 클래스 (0) | 2021.12.07 |
[모의 필기테스트] 오답노트 & 정리 (0) | 2021.12.07 |
java Class (0) | 2021.12.06 |