organize/자바

Java 16

001cloudid 2024. 5. 1. 16:08
728x90

메서드 예외 선언

예외 처리 방법 : try-catch문(직접 처리), 예외 선언(예외 떠넘기기, 알리기), 은폐

메서드 예외 선언 : 메서드가 호출 시 발생가능한 예외를 호출하는 쪽에 알리는 것

※예외를 발생시키는 키워드 throw와 예외를 메서드에 선언할 때 쓰이는 throws 구분

 

		//메서드에 예외 선언
		void method() throws Exception1, Exception2, .... , ExceptionN{
		 //메서드 내용
		}
		
		//method()에서 Exception 클래스 예외 발생 가능
		void method() throws Exception {
		 //메서드 내용
		}

 

package chapter08;

import java.io.File;

public class Study05Ex1 {

	static File createFile(String fileName) throws Exception{
		if(fileName == null || fileName.equals(""))
			throw new Exception("파일이름이 유효하지 않습니다.");
		File file = new File(fileName); //File 클래스의 객체를 만듦
		//File 객체의 createNewFile메서드를 이용해 실제 파일을 생성
		file.createNewFile();
		return file; //생성된 객체의 참조를 반환
	}
	
	public static void main(String[] args) {
		
		try {
			File file = createFile(args[0]);
			System.out.println(file.getName() + "파일이 성공적으로 생성");
		} catch (Exception e) {
			System.out.println(e.getMessage() + " 다시 입력해주시기 바랍니다.");
		}

	}

}

 

finally

예외 발생여부와 관계없이 수행되어야 하는 코드를 넣음

		//예외 발생여부와 관계없이 수행되어야 하는 코드를 넣음
		try {
			//예외가 발생할 가능성이 있는 문장
		} catch (Exception e) {
			//예외처리를 위한 문장
		} finally {
			//예외 발생여부에 관계없이 항상 수행되어야하는 문장들을 넣음
			//finally 블럭은 try-catch문의 맨 마지막에 위치
		}
		//try 블럭 안에 return문이 있어 try블럭을 벗어날 때도 finally 블럭이 실행

 

사용자 정의 예외 만들기

직접 예외 클래스를 정의할 수 있음

조상은 Exception과 RuntimeException 중에서 선택
※Exception 사용자가 발생시키는 예외, RuntimeException 프로그래머의 실수로 발생시키는 예외

 

		class CustomException extends Exception{
			CustomException(String msg) { //문자열을 매개변수로 받는 생성자
				super(msg); //조상인 Exception 클래스의 생성자 호출
			}
		}

 

예외 되던지기(exception re-throwing)

예외 처리한 후 다시 예외를 발생시키는 것

호출한 메서드와 호출된 메서드 양쪽 모두에서 예외처리하는 것

package chapter08;
//예외 던지기
public class Study06Ex1 {

	static void method1() throws Exception{
		try {
			throw new Exception();
		} catch (Exception e) {
			System.out.println("method1() 메서드에서 예외가 처리됨");
			throw e;
		}
	}
	
	public static void main(String[] args) {
		try {
			method1();
		} catch (Exception e) {
			System.out.println("main() 메서드에서 예외가 처리됨");
		}
		
	}

}

 

연결된 예외(chained exception)

한 예외가 다른 예외를 발생시킬 수 있음

예외 A가 예외 B를 발생시키면 A는 B의 원인 예외(cause exception)

Throwable initCause(Throwable cause) 지정한 예외를 원인 예외로 등록

Throwable getCause() 원인 예외를 반환


hashCode()

객체의 해시코드(hash code)를 반환하는 메서드 *해시코드 : 정수값
Object 클래스의 hashCode()는 객체의 주소를 int로 변환해서 반환
equals()를 오버라이딩하면, hashCode()도 오버라이딩해야함. equals() 결과가 true인 두 객체의 해시코드는 같아야하기 때문

 

String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1.equals(str2)); //true
System.out.println(str1.hashCode());
System.out.println(str2.hashCode());

 

System.identityHashCode(Object obj)는 Object클래스의 hashCode()와 동일. 객체마다 다른 해시코드를 반환

System.identityHashCode(System.identityHashCode(str1));
System.identityHashCode(System.identityHashCode(str2));

 

toString()

toString() : 객체를 문자열(String)으로 변환하기 위한 메서드

public String toString() {	//Object클래스의 toString()
	return getClass().getName()+"@"+Integer.toHexString(hashCode());
}

 

package chapter09;

class CardS1E1{
	String kind;
	int number;
	
	CardS1E1(){
		this("SPADE", 1);
	}
	
	CardS1E1(String kind, int number){
		this.kind = kind;
		this.number = number;
	}
}


public class Study01Ex1 {
	
	public static void main(String[] args) {

//		public String toString() {	//Object클래스의 toString()
//		return getClass().getName()+ "@" +Integer.toHexString(hashCode());
			// 설계도객체. 클래스이름 + at(위치) +         16진수     객체주소
//		}
	
		
		System.out.println(new CardS1E1().toString());
		System.out.println(new CardS1E1().toString());
		
		
	}

}

 

toString()의 오버라이딩

iv값을 이용해서 출력하도록 오버라이딩

public String toString(){
	return "kind : " + kind + ", number " + number;
}

 

※객체 == iv 집합. 객체를 문자열로 변환한다는 것은 iv의 값을 문자열로 변환한다는 것과 같음

 

package chapter09;

import java.util.Objects;

class CardS1E1{
	String kind;
	int number;
	
	CardS1E1(){
		this("SPADE", 1);
	}
	
	CardS1E1(String kind, int number){
		this.kind = kind;
		this.number = number;
	}
	
	//equals()를 오버라이딩하면 hashCode()도 오버라이딩 해야함
	public int hashCode() {
		return Objects.hash(kind,number);
		//Objects 클래스는 객체와 관련된 유용한 메서드를 제공하는 유틸 클래스
		//int hash(Object... values){...} 매개변수가 가변인자(Obejct...)기 때문에 호출 시 지정하는 값의 개수가 정해져 있지 않음
	}
	
	//Object 클래스의 toString() 오버라이딩
	public String toString() {
		return "kind : " + kind + ", number : " + number;
	}
	
	//Object 클래스의 equals() 오버라이딩
	public boolean equals(Object obj) {
		if(!(obj instanceof CardS1E1)) { 
			return false;
		}
			CardS1E1 c = (CardS1E1)obj;
			return this.kind.equals(c.kind) && this.number == c.number;
	}
}


public class Study01Ex1 {
	
	public static void main(String[] args) {

//		public String toString() {	//Object클래스의 toString()
//		return getClass().getName()+ "@" +Integer.toHexString(hashCode());
			// 설계도객체. 클래스이름 + at(위치) +         16진수     객체주소
//		}
		
		CardS1E1 c1 = new CardS1E1();
		CardS1E1 c2 = new CardS1E1();
		
		System.out.println(c1.equals(c2));
		
		System.out.println(c1.hashCode());
		System.out.println(c2.hashCode());
		
		
	}

}

 

728x90

'organize > 자바' 카테고리의 다른 글

Java 18  (0) 2024.05.03
Java 17  (0) 2024.05.02
Java 15  (0) 2024.04.30
Java 14  (0) 2024.04.28
Java 13  (0) 2024.04.25