Nishant Girdharwal

Frontend Developer Software Developer || Fascinated by tech trends || Building usable systems that work on web and mobile.

try…catch uses in Javascript

The try…catch statement marks a block of statements to try and specifies a response should an exception be thrown.

Syntax:

try {
  try_statements
}
catch (exception_var) {
  catch_statements
}
finally {
  finally_statements
}

Description

try_statements

The statements to be executed.

catch_statements

Statement that is executed if an exception is thrown in the try-block.

exception_var

An optional identifier to hold an exception object for the associated catch-block.

finally_statementsStatements that are executed after the try statement completes. These statements execute regardless of whether an exception was thrown or caught.

Unconditional catch-block

  • When a catch-block is used, the catch-block is executed when any exception is thrown from within the try-block

For example: 


try {
	throw ‘myException’;  
} catch (error) {
	// statements to handle any exception
	console.log(error) // pass objection object to error handler
}

Conditional catch-block

  • You can create “Conditional catch-blocks” by combining try…catch blocks with if…else if…else structures, 

For example: 


try {
  myRoutine();
} catch (e) {
  if (e instanceof RangeError) {
    // statements to handle this very common expected error
  } else {
    throw e;  // re-throw the error unchanged
  }
}

The exception identifier

  • When an exception is thrown in the try-block, exception_var (i.e., the e in catch (e)) holds the exception value. 
  • You can use this identifier to get information about the exception that was thrown.

For example: 


function isValidJSON(text) {
  try {
    JSON.parse(text);
    return true;
  } catch {
    return false;
  }
}

The Finally Block

  • The finally-block contains statements to execute after the try-block and catch-block(s) execute, but before the statements following the try…catch…finally-block
  • Note that the finally-block executes regardless of whether an exception is thrown.

For example: 

openMyFile();
try {
  // tie up a resource
  writeMyFile(theData);
} finally {
  closeMyFile(); // always close the resource
}
Share