정의 하고 처리 할 수 있기때문에 대응이 가능하다.
의존관계 발생
class OurBadException extends Exception {
public OurBadException() {
super("위험한 행동을 하면 예외처리를 꼭 해야합니다!");
}
}
class OurClass {
private final Boolean just = true;
// 신규 문법 throws!
public void thisMethodIsDangerous() throws OurBadException {
if (just) {
// 신규 문법 throw!
throw new OurBadException();
}
}
}

throws 키워드를 통해 해당 예외가 발생할수 있다 명시.throw 키워드를 통해 예외객체를 생성시켜 예외발생.public class StudyException {
public static void main(String[] args) {
OurClass ourClass = new OurClass();
try {
// 1. 위험한 메소드의 실행을 "시도" 해 봅니다.
// "시도" 해보는 코드가 들어가는 블럭입니다.
ourClass.thisMethodIsDangerous();
} catch (OurBadException e) {
// 2. 예외가 발생하면, "잡아서" handling 합니다.
// 예외가 발생하는경우 "handling" 하는 코드가 들어가는 블럭입니다.
// 즉 try 블럭 내의 구문을 실행하다가 예외가 발생하면
// 예외가 발생한 줄에서 바로 코드 실행을 멈추고
// 여기 있는 catch 블럭 내의 코드가 실행됩니다.
System.out.println(e.getMessage());
} finally {
// 3. 예외의 발생 여부와 상관없이, 실행시켜야 하는 코드가 들어갑니다.
// 무조건 실행되는 코드가 들어가는 블럭입니다.
System.out.println("우리는 방금 예외를 handling 했습니다!");
}
}
}
try - catch - finally 구문을 통해 예외를 핸들링 가능하다.
// 연결된 예외
public class main {
public static void main(String[] args) {
try {
// 예외 생성
NumberFormatException ex = new NumberFormatException("가짜 예외이유");
// 원인 예외 설정(지정한 예외를 원인 예외로 등록)
ex.initCause(new NullPointerException("진짜 예외이유"));
// 예외를 직접 던집니다.
throw ex;
} catch (NumberFormatException ex) {
// 예외 로그 출력
ex.printStackTrace();
// 예외 원인 조회 후 출력
ex.getCause().printStackTrace();
}
}
}
// 출력
Caused by: java.lang.NullPointerException: 진짜 예외이유
initCause() : 지정예외를 원인예외로 등록하는 메소드.getCause() : 원인예외를 반환하는 메소드.// checked exception 을 감싸서 unchecked exception 안에 넣습니다.
throw new RuntimeException(new Exception("이것이 진짜 예외 이유 입니다."));

public String getDataFromAnotherServer(String dataPath) {
try {
return anotherServerClient.getData(dataPath).toString();
} catch (GetDataException e) {
return defaultData;
}
}

public void someMethod() throws Exception { ... }
public void someIrresponsibleMethod() throws Exception {
this.someMethod();
}

public void someMethod() throws IOException { ... }
public void someResponsibleMethod() throws MoreSpecificException {
try {
this.someMethod();
} catch (IOException e) {
throw new MoreSpecificException(e.getMessage());
}
}
참조 :
https://devlog-wjdrbs96.tistory.com/351
https://inpa.tistory.com/entry/JAVA-%E2%98%95-Exception-Handling-%EC%98%88%EC%99%B8%EB%A5%BC-%EC%B2%98%EB%A6%AC%ED%95%98%EB%8A%94-3%EA%B0%80%EC%A7%80-%EA%B8%B0%EB%B2%95
public class Generic {
public Object plusReturnFunction(Object a,Object b) { ... }
}
// 1.
public class Generic<T> {
// 2.
private T t;
// 3.
public T get() {
return this.t;
}
public void set(T t) {
this.t = t;
}
public static void main(String[] args) {
// 4.
Generic<String> stringGeneric = new Generic<>();
// 5.
stringGeneric.set("Hello World");
String tValueTurnOutWithString = stringGeneric.get();
System.out.println(tValueTurnOutWithString);
}
}
static T get() { ... } // 에러
static void set(T t) { ... } // 에러
구체적으로 적용가능.public class ParkingLot<T extends Car> { ... }
ParkingLot<BMW> bmwParkingLot = new ParkingLot();
ParkingLot<Iphone> iphoneParkingLot = new ParkingLog(); // error!


// 또는 ..
static <T> void sort(List<T> list, Comparator<? super T> c) { ... }
<T>로 클래스와 메소드를 동일하게 적용했다 하더라도 별개의 타입변수로 취급한다.
Integer num = new Integer(17); // Boxing
int n = num.intValue(); // UnBoxing
Character ch = 'X'; // AutoBoxing
char c = ch; // AutoUnBoxing
답안 :
package week04;
import java.text.ParseException;
import java.util.regex.Pattern;
public class Parser {
private static final String OPERATION_REG = "[+\\-*/]";
private static final String NUMBER_REG = "^[0-9]*$";
private final Calculator calculator = new Calculator();
public Parser parseFirstNum(String firstInput) throws BadInputException {
if (firstInput.matches(NUMBER_REG)) {
this.calculator.setFirstNumber(Integer.parseInt(firstInput));
} else {
throw new BadInputException("정수값");
}
return this;
}
public Parser parseSecondNum(String secondInput) throws BadInputException {
if (secondInput.matches(NUMBER_REG)) {
this.calculator.setSecondNumber(Integer.parseInt(secondInput));
} else {
throw new BadInputException("정수값");
}
return this;
}
public Parser parseOperator(String operationInput) throws BadInputException {
if (operationInput.matches(OPERATION_REG)) {
switch (operationInput) {
case "+" -> this.calculator.setOperation(new AddOperation());
case "-" -> this.calculator.setOperation(new SubstractOperation());
case "*" -> this.calculator.setOperation(new MultiplyOperation());
case "/" -> this.calculator.setOperation(new DivideOperation());
}
} else {
throw new BadInputException("연산자");
}
return this;
}
public double executeCalculator() {
return calculator.calculate();
}
}
package week04;
public class Main {
public static void main(String[] args) {
boolean calculateEnded = false;
CalculatorApp calculator = new CalculatorApp();
while (!calculateEnded) {
try {
calculator.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}