예외는 프로그래밍 언어 중 문법적 혹은 잘못된 참조 등으로 발생할 수 있는 상황을 의미한다.
프로그래밍에서 사용할 수 있는 예외적인 상황에서 에러를 던지는 것(예외를 발생시키는 것)은 좋은 습관이다.
자바스크립트에서는 예외를 Error
클래스를 통해 발생시킬 수 있다.
throw
키워드를 사용할 수 있으며, try
/ catch
를 통해 예외를 처리할 수 있다.try {
throw new Error('something bad happened');
} catch(e) {
console.error(e);
}
occur-error.method.ts
export const occurErrorMethod: () => void = ():
void => {
throw new Error('Occurred Error');
}
index.ts
import {occurErrorMethod} from "./occur-error.method";
try {
occurErrorMethod();
} catch (e) {
console.error(`Error message : ${e.message}`);
}
// 제네릭 인터페이스 구문
interface IValuable<T> {
value: T
}
valuable.ts
export interface IValuable<T> {
value: T;
}
export class Valuable<T> implements IValuable<T> {
constructor(public value: T) {
}
}
print-value.ts
import {IValuable} from "./valuable";
export const printValue = <T>(v: IValuable<T>): void => console.log(v.value);