프로그램 실행 중 발생하는 오류 중에서 처리가 가능한 것을 의미한다.
에러: 개발자가 조치를 취할 수 없는 수준
ex) 메모리 부족, JVM 동작 이상
컴파일 에러: 컴파일 시 발생하는 에러
ex) 오타, 잘못된 자료형 등
런타임 에러: 프로그램 실행 도중에 발생하는 에러
로직 에러: 실행은 되지만 의도와는 다르게 동작하는 에러
예외: 다른 방식으로 처리 가능한 오류
ex) 입력값 오류, 네트워크 문제
예외가 발생했을 때 이를 적절히 처리하여 프로그램이 비정상적으로 종료되는 것을 막는 방법
예외 발생 시, 적절하게 처리하기 위해 자바에서 제공하는 예외처리 문법
try{
예외가 발생할 수 있는 명령;
}
catch(발생할 수 있는 예외 클래스명){
예외 발생 시 실행할 명령;
}
public static void main(String[] args) {
try {
int []a= {2,0};
int b=4;
int c=b/a[2]; // 배열의 인덱스가 1까지밖에 없어서 생기는 오류
System.out.println(c);
}
catch(ArithmeticException e) {
System.out.println("산술 오류 발생");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("배열 길이 오류 발생");
}
System.out.println("예외처리 공부");
}
}
try-catch문에 선택적으로 추가할 수 있는 문법으로, 오류가 발생하든 하지 않든 무조건 실행하는 구문
try{
예외가 발생할 수 있는 명령;
}
catch(발생할 수 있는 예외 클래스명){
예외 발생 시 실행할 명령;
}
finally{
예외가 발생하든 안하든 무조건 실행하는 명령;
}
public static void main(String[] args) {
int a = 0;
int b=2;
try {
System.out.println("외부로 접속");
int c=b/a;
}
catch(ArithmeticException e){
System.out.println("오류가 발생하였습니다.");
}
finally {
System.out.println("무조건 연결해제");
}
}
}
자바에서의 예외는 Exception 클래스의 객체이다.
→ 자바는 객체지향 언어이기 때문에 예외도 객체로 처리한다.
<한 번에 모든 예외처리 하는 방법>
try{
예외가 발생할 수 있는 명령;
}
catch(Exception e){
예외 발생 시 처리할 명령;
}
고의적으로 예외 발생시키는 방법
public static void main(String[] args) {
try {
Exception e = new Exception("고의 예외");
throw e; //고의적으로 예외를 던지겠다.
}
catch(Exception e) {
System.out.println("예외발생");
System.out.println(e.getMessage());
}
}
}
##출력값
예외 발생
고의 예외
void method() throws Exception{...}
public static void main(String[] args) {
try {
methodA();
}
catch(Exception e) {
System.out.println("메인에서 처리");
}
}
public static void methodA() throws Exception{
methodB();
}
public static void methodB() throws Exception{
methodC();
}
public static void methodC() throws Exception{
Exception e = new Exception();
throw e; // 예외발생
}
}
public static void main(String[] args) {
try {
System.out.println("외부 try...");
try {
System.out.println("내부 try...");
Exception e = new Exception();
throw e;
}
catch(Exception e) {
System.out.println("(내부 try-catch) exception: " + e);
System.out.println("예외던지기 한 번 더:");
throw e;
}
finally {
System.out.println("finally 구문 출력");
}
}
catch(Exception e) {
System.out.println("(외부 try-catch) exception: " +e);
}
System.out.println("종료");
}
}
기존 예외클래스로 예외 표현이 불가능할 경우, 나만의 예오 클래스를 만들어 사용할 수 있다.(예외 클래스를 상속받아 사용)
public static void main(String[] args) {
int age= -19;
try {
ticketing(age);
}
catch(AgeException e) {
e.printStackTrace(); //가지고 있는 오류를 출력하겠다.
}
}
public static void ticketing(int age) throws AgeException{
if (age<0) {
throw new AgeException("나이 입력이 잘못되었습니다.");
}
}
}
class AgeException extends Exception{
public AgeException() {}
public AgeException(String message) {
super(message);
}
}