오류(Error) : 시스템의 오류, JVM 오류(통제 불가)
예외(Exception) : 코드 상의 오류(통제 가능한 오류)
Throwable
Error Exception
예) java.io.IOException / 파일을 읽을때, 쓸때 (FileInputStream, FileOutputStream)
java.io.FileNotFoundException
- 예외있든 없든 처리가 안되어 있으면 컴파일 X
- 예외의 체크는 컴파일시 체크, 예외가 있으면 컴파일 X
- 예외가 발생하든 안하든 반드시 적절한 예외 처리가 필요한 예외
- 엄격한 예외, 형식을 매우 중시
public class Ex02 { public static void main(String[] args) { //Thorw new FileNotFoundException(...) //무조건 Thorw가 되어있다. FileInputStream fis = new FileInputStream("a.txt"); }
예) java.lang.ArithmethicException : 0으로 나눌때 발생
- 예외가 발생하더라도 컴파일 O, class 파일 생성
- 예외의 체크는 실행 중 체크, 실행이 되려면? class 파일 필요(컴파일은 된다...)
- 유연한 예외, 형식은 X
java.exe : 클래스파일 실행
javac.exe : java -> class 컴파일
try {
// 예외가 발생할 가능성이 있는 코드
} catch (예외 객체 ....) {
// 예외 발생시 처리할 코드
}
public class Ex02 {
public static void main(String[] args) {
//Thorw new FileNotFoundException(...)
try{
FileInputStream fis = new FileInputStream("b.txt");
System.out.println("파일처리");
}catch(FileNotFoundException e){
System.out.println("예외발생");
};
System.out.println("중요한 실행코드");
}
}
public class Ex01 {
public static void main(String[] args) {
try{
int num1 = 10;
int num2 = 0;
int result= num1 / num2;
System.out.println(result);
} catch (ArithmeticException e){
e.printStackTrace();
}
System.out.println("매우중요한코드");
}
}
예외 발생
throw 예외객체;
예외, 오류 -> 원인을 확인을 하는것이 중요
예외 클래스 주요 메서드 : 정보확인
java.lang.Throwable
String getMessage() : 오류 메세지 확인void printStackTrace() : 원인발생한 위치부터 ~ 파생된 위치...public class Ex02 {
public static void main(String[] args) {
//Thorw new FileNotFoundException(...)
try{
FileInputStream fis = new FileInputStream("b.txt");
}catch(FileNotFoundException e){
String message = e.getMessage();
System.out.println(message);
};
}
//getMessage()을통해 오류의 원인을 확인.
//> b.txt (지정된 파일을 찾을 수 없습니다)
try {
} catch (...) {
...
} finally {
// 예외가 발생하든 안하든 항상 실행되는 코드
// return 하더라도 코드가 실행
}
public class Ex04 {
public static void main(String[] args) {
try{
FileInputStream fis = new FileInputStream("d.txt");
}catch (FileNotFoundException e){
e.printStackTrace();
}finally {
System.out.println("finally");
}
}
}
FileInputStream, FileOutputStream, Connection, PrepareStatement finally에 자원해제를 해서 오류가 발생하든 안하든 해제를 하도록 해야한다.
public class Ex04 {
public static void main(String[] args) {
FileInputStream fis = null;
try{
fis = new FileInputStream("a.txt");
System.out.println("파일작업");
}catch (IOException e){
System.out.println(e);
e.printStackTrace();
}finally {
System.out.println("finally");
if (fis != null){
try{
fis.close();
} catch (IOException e)
{
}
}
System.out.println("자원해제완료");
}
}
}
try ( 해제할 자원 객체;
해제할 자원 객체 ...) {
// 예외가 발생할 가능성이 있는 코드
} catch(예외 객체 ...) {
}
public class Resource implements AutoCloseable{
@Override
public void close() throws Exception {
System.out.println("자원해제!");
}
}
public class Ex01 {
public static void main(String[] args) {
try(Resource res = new Resource()){
//res가 AutoCloasable 인터페이스 구현 객체인지 체크 → close()메서드 자동호출
/* 로직
AutoCloseable auto = res;
auto.close();
*/
}catch(Exception e){
e.printStackTrace();
}
}
}
자원 자동해제의 기준
AutoCloseable 인터페이스의 구현 클래스 :close() 메서드를 자동 호출
참고)
instanceof
예외가 다중 발생할 때에는 catch문을 다중으로 사용하여 처리한다.
public class Ex01 {
public static void main(String[] args) {
try{
int num1 = 10;
int num2 = 0;
int result= num1 / num2;
String str = null;
System.out.println(str.toUpperCase());
System.out.println(result);
} catch (ArithmeticException e){
e.printStackTrace();
} catch(NullPointerException e){
e.printStackTrace();
} catch(Exception e){
e.printStackTrac();
System.out.println("매우중요한코드");
}
}
Exception
public class UserPwException extends Exception{
public UserPwException(String message){
super(message);
}
}
- - - - - - - - - - - - - - - - - - - - -
public class UserIdException extends Exception {
public UserIdException(String message){
super(message);
}
}
- - - - - - - - - - - - - - - - - - - - -
public class LoginService {
public void login(String userId, String userPW) {
//userID = user01, userPw = 123456
try {
if (!userId.equals("user01")) {
throw new UserIdException("아이디가 일치하지않음");
}
if (!userPW.equals("123456")) {
throw new UserPwException("비밀번호가 일치하지않음");
}
System.out.println("로그인성공");
}catch (UserIdException | UserPwException e){
System.out.println(e.getMessage());
}
}
}
- - - - - - - - - - - - - - - - - - - - -
public class Ex01 {
public static void main(String[] args) {
LoginService log = new LoginService();
log.login("user01","123456");
}
}