Skip to content

Instantly share code, notes, and snippets.

@yanfeng42
Created September 29, 2021 02:02
Show Gist options
  • Save yanfeng42/bff25ff37a62bec8c092edf136ec2cbf to your computer and use it in GitHub Desktop.
Save yanfeng42/bff25ff37a62bec8c092edf136ec2cbf to your computer and use it in GitHub Desktop.
SmartDate 有感: 我支持 所有异常 都是 受检异常
package life.yanfeng.study.algorithm;
import edu.princeton.cs.algs4.StdOut;
public class SmartDate {
private final int month;
private final int day;
private final int year;
public SmartDate(int m, int d, int y) throws RuntimeException
{
// 校验规则, 基于 P56 页首描述的简易规则.
if (d < 0 || d > 31) {
throw new RuntimeException("illegal day");
}
if (m< 0 || m > 15) {
throw new RuntimeException("illegal month");
}
if (y <= 0) {
throw new RuntimeException("illegal year");
}
month = m;
day = d;
year = y;
}
public int month() {
return month;
}
public int day() {
return day;
}
public int year() {
return year;
}
public String toString() {
return month() + "/" + day() + "/" + year();
}
public static void main(String[] args) {
SmartDate date = new SmartDate(-1, 2, 3);
StdOut.println(date);
}
}
@yanfeng42
Copy link
Author

"受检异常" 就是函数调用方, 必须自己 try-catch 的异常, 否则静态检查,就无法通过.

Java 中区分 "受检异常" "非受检异常"; Kotlin objc中, 都是 非受检异常; Swift 中都是 "受检异常".

我支持 Swift 中的处理: 所有异常, 必须显式 处理; 提在不关心异常的场景, 供 as? 等语法糖, 降低 处理异常的成本.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment