Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Errors - Throw, Try and Catch

JavaScript Errors - throw, try and catch


try The statement tests a block of code for errors.

catch The statement handles errors.

throw The statement creates a custom error.

finally The statement executes after the try and catch statements, whether or not an exception is thrown.


 JavaScript Errors

Various errors occur when the JavaScript engine executes JavaScript code.

It may be a syntax error, usually a coding mistake or typo made by the programmer.

It may be a misspelling or a missing feature of the language (possibly due to browser differences).

It may be an error caused by incorrect output from the server or user.

Of course, it may also be due to many other unpredictable factors.


JavaScript throwing (throw) errors

When an error occurs, when something goes wrong, the JavaScript engine usually stops and generates an error message.

The technical term for this situation is: JavaScript willThrowsan error.


JavaScript try and catch

try The statement allows us to define a block of code that performs error testing at runtime.

catch The statement allows us to define a block of code to be executed when an error occurs in the try block.

JavaScript Statements try and catch They appear in pairs.

Syntax

try

{

...

//

Throwing an exception

}

catch

(

e

)

{

...

//

Catching and handling exceptions

}

finally

{

...

//

Final handling

}

Example

In the example below, we intentionally wrote a typo in the code of the try block.

The catch block catches errors in the try block and executes code to handle them.

Example

var

txt

=

"

"

;

function

message

(

)

{

try

{

adddlert

(

"

Welcome guest!

"

)

;

}

catch

(

err

)

{

txt

=

"

There is an error on this page.

\n

\n

"

;

txt

+=

"

Error description:

"

err

.

message

"

\n

\n

"

;

txt

+=

"

Click OK to continue.

\n

\n

"

;

alert

(

txt

)

;

}

}

Try it »

The finally Statement

The finally statement executes the block of code regardless of whether an exception was thrown in the preceding try and catch.

Example

function

myFunction

(

)

{

//

Get element

const

messageElement

=

document

.

getElementById

(

"

p01

"

)

;

const

inputElement

=

document

.

getElementById

(

"

demo

"

)

;

//

Clear previous messages

messageElement

.

innerHTML

=

"

"

;

//

Get input value and trim whitespace

const

rawValue

=

inputElement

.

value

.

trim

(

)

;

try

{

//

  1. Check if empty

if

(

rawValue

===

"

"

)

{

throw

new

Error

(

"

Input cannot be empty, please enter a number

"

)

;

}

//

  1. Check if it is a valid number

if

(

isNaN

(

rawValue

)

)

{

throw

new

Error

(

"

Please enter a valid number (e.g., 5, 10.5, -3)

"

)

;

}

//

Convert to number

const

x

=

Number

(

rawValue

)

;

//

  1. Check if it is an integer (can be adjusted as needed)

if

(

!

Number

.

isInteger

(

x

)

)

{

throw

new

Error

(

"

Please enter an integer (decimals are not supported)

"

)

;

}

//

  1. Check the number range (can be adjusted as needed)

if

(

x

10

)

{

throw

new

Error

(

`Number $

{

x

}

is too large, please enter a

5

10

number between

)

;

}

if

(

x

<

5

)

{

throw

new

Error

(

`Number $

{

x

}

is too small, please enter a

5

10

number between

)

;

}

//

  1. Check for the special case of negative numbers

if

(

x

<

0

)

{

throw

new

Error

(

"

Please enter a positive number (negative numbers are not supported)

"

)

;

}

//

All validations passed

messageElement

.

innerHTML

= `Validation passed! The number you entered is: $

{

x

}

`;

messageElement

.

style

.

color

=

"

green

"

;

//

Other actions can be performed on success

console

.

log

(

`User entered a valid number: $

{

x

}

`

)

;

}

catch

(

err

)

{

//

Display error message

messageElement

.

innerHTML

= `Error: $

{

err

.

message

}

`;

messageElement

.

style

.

color

=

"

red

"

;

//

Optional: log the error to the console

console

.

error

(

"

Input validation failed:

"

,

err

.

message

)

;

}

finally

{

//

Clear the input box whether successful or not

inputElement

.

value

=

"

"

;

//

Optional: refocus the input box so the user can re-enter

inputElement

.

focus

(

)

;

}

}

Try it »


The throw statement

The throw statement allows us to create custom errors.

The correct technical term is: create orThrowing an Exception(exception)。

If you use throw together with try and catch, you can control the program flow and generate custom error messages.

Syntax

throw

exception

An exception can be a JavaScript string, number, boolean, or object.

Example

This example checks the value of the input variable. If the value is wrong, an exception (error) is thrown. The catch will capture this error and display a custom error message:

Example

function

myFunction

(

)

{

var

message

,

x

;

message

=

document

.

getElementById

(

"

message

"

)

;

message

.

innerHTML

=

"

"

;

x

=

document

.

getElementById

(

"

demo

"

)

.

value

;

try

{

if

(

x

==

"

"

)

throw

"

The value is empty

"

;

if

(

isNaN

(

x

)

)

throw

"

Not a number

"

;

x

=

Number

(

x

)

;

if

(

x

<

5

)

throw

"

Too small

"

;

if

(

x

10

)

throw

"

Too large

"

;

}

catch

(

err

)

{

message

.

innerHTML

=

"

Error:

"

err

;

}

}

Try it »

Note that if the getElementById function fails, the example above will also throw an error.