user728630 user728630 - 1 month ago 6x
TypeScript Question

Catch block is not executed in typescript

I have a simple pipe which formats passed parameters to date format. If it's an invalid conversion then it throws an error. But it never actually throws an error to fall in the catch block.

import {PipeTransform, Pipe} from 'angular2/core';

name: 'formatDate'

export class FormatDatePipe implements PipeTransform {
transform(value: string): any {
let date: string;
try {
date = new Date(value).toLocaleDateString();
catch (Exception) {
return value;
finally {
return date;

Why is the catch block not executed even when an invalid date is passed?


If you pass an invalid date to the constructor then it does not throw an error for all inputs, it depends.

You can read about this in here: Fall-back to implementation-specific date formats, which links to this "rough outline on how the parsing works".

But it seems that if it does not throw an error then it returns Invalid Date, so you can do this:

try {
    date = new Date(value).toLocaleDateString();
    if (date === "Invalid Date") {
        throw new Error(`invalid date value ${ value }`);

And this way it will throw an error even in such cases.