ExpertiDict

JavaScript · Essencial · Inglês · Técnico

throw

/θɹoʊ/palavra-chave

Instrução que interrompe a execução e lança um valor como exceção, que sobe a pilha até um catch. Aceita qualquer valor, mas o ideal é lançar objetos Error.

Onde usar

Usada para sinalizar entrada inválida e falhas. Em code review, pede-se throw new Error com mensagem útil em vez de lançar strings, que não trazem stack trace.

Em código

function dividir(a, b) {
  if (b === 0) throw new RangeError('zero');
  return a / b;
}
try { dividir(1, 0); }
catch (e) { console.log(e.message); }

Exemplos

Throw a RangeError when the index is out of bounds.

Lance um RangeError quando o índice estiver fora dos limites.

Don't throw a string, throw an Error.

Não lance uma string, lance um Error.

Cuidado

Lançar strings ou objetos simples: perdem o stack trace e dificultam o debug.

Sinônimos

lançar exceção

Origem

Do inglês throw, 'lançar'.

Veja também

Todos os termos de JavaScript