Jam's story

예외처리 본문

자바

예외처리

애플쩀 2022. 2. 2. 22:11
NullPointerException

객체가 없는 상태에서 사용하려고 할때 

 

ArrayIndexOutOfBoundsException

배열-인덱스범위 초과 

매개값을 주지않은 인덱스사용 

밑의 사진의 곳에서 값을 줄 수 있다. 

 

NumberFormatException

문자열 -> 숫자 로 변경하는 경우에 오류 

ClassCastException

상위클래스-하위클래스

인터페이스-구현클래스 간에 타입변환을 할 때, 대입된 객체가 아닌 다른 객체로 타입변환이 되면 오류 

 

그래서 [상위| 인터페이스 ]instance of  [ 하위|구현클래스 ]로 확인한 후 바꾸는 것이 좋다. 

package twoInterface;

public class ClassCastEx {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Dog dog=new Dog();
		ChangeDog(dog);
		
		Cat cat =new Cat();
		ChangeDog(cat);
	}
	public static void ChangeDog(Animal animal) {
		if(animal instanceof Dog) {
			Dog dog=(Dog)animal;
		}
	}

}
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}

 

try -> 무조건실행됨 

catch -> 에러가 발생하면 여기를 거침

finally -> 에러가 있건 없건 무조건 실행 

try {

}catch(예외클래스 e){

}finally{

}

 

Comments