sitelink4 http://1 
extra_vars4 ko 
extra_vars5 http://The Error object and throwing your own errors 
extra_vars6 sitelink1 

The Error Object

As promised, we're going to take a closer look at the Error object that gets passed into the catch clause to see just what we can extract from it in an event of an error. The Error object in all browsers support the following two properties:

  1. name: The name of the error, or more specifically, the name of the constructor function the error belongs to.
  2. message: A description of the error, with this description varying depending on the browser.

try{
 document.body.filters[0].apply()
}
catch(e){
 alert(e.name + "n" + e.message)
}

Demo:

Six possible values can be returned by the name property, which as mentioned correspond to the names of the error's constructors. They are:

Error NameDescription
EvalErrorAn error in the eval() function has occurred.
RangeErrorOut of range number value has occurred.
ReferenceErrorAn illegal reference has occurred.
SyntaxErrorA syntax error within code inside the eval() function has occurred. All other syntax errors are not caught by try/catch/finally, and will trigger the default browser error message associated with the error. To catch actual syntax errors, you may use the onerror event.
TypeErrorAn error in the expected variable type has occurred.
URIErrorAn error when encoding or decoding the URI has occurred (ie: when calling encodeURI()).

This level of detail may be useful when you wish to sniff out a specific type of error in your catch clause. In the below, no DIV on the page exists with ID="mydiv". When trying to set its .innerHTML property, a TypeError occurs, since we're trying to assign the .innerHTML property to a null object:

try{
 document.getElementById("mydiv").innerHTML='Success' //assuming "mydiv" is undefined
}
catch(e){
 if (e.name.toString()=="TypeError") //evals to true in this case
  //do something
}

Ok, so maybe it's not that useful most of the time, but you just never know.

Throwing your own errors (exceptions)

Instead of waiting for one of the 6 types of errors above to occur before control is automatically transferred from the try block to the catch block, you can also explicitly throw your own exceptions to force that to happen on demand. This is great for creating your own definitions of what an error is and when control should be transferred to catch.

To throw an error, invoke, well, the throw statement inside your try/catch/finally blocks. The syntax is:

throw myerrorobject

Where myerrorobject can in fact be anything from a string, number, Boolean, to a new or one of the 6 default Error Constructor functions. What myerrorobject is set to mainly just affects what error.name and error.message returns in your catch clause. Most commonly you would just throw a new Error object:

  • throw new Error("Oh oh, an error has occured")

Lets see a meaningful example of throw in action:

function entrycheck(){
 try{
  var agecheck=prompt("This movie is rated PG-13. Please enter your age before continuing:")
  if (isNaN(parseInt(agecheck)))
   throw new Error("Please enter a valid age")
  else if (agecheck<13)
   throw new Error("Sorry, but you are too young for this movie")
  alert("Enjoy the movie!")
 }
 catch(e){
  alert(e.name+" "+e.message)
 }
}

Demo:

Try entering a none numeric value (ie: "haha") or a number less than 13 (ie: 11). In both cases, by using throw, control is instantly transferred to catch, with e.message displaying a different message. Technically entering a string or number less than 13 certainly doesn't constitute an exception in JavaScript, though for our purpose here, they should. That's how throw can be useful- when you need to specify your own parameters of what an error is inside try/catch/finally.

As mentioned, there are a number of other things apart from new Error() you can throw, which changes the contents of the error object passed into catch. The following are all valid throws:

  • throw "An error has occurred"
  • throw true
  • throw new Error("I detect an error!")
  • throw new SyntaxError("Your syntax is no good")

In the last instance, you can substitute SyntaxError with one of the 6 Error constructor function names to throw a specific type of error. In our age check example above, we could have thrown a SyntaxError when the value entered was a string, and a RangeError when the value was less than 13:

function entrycheck(){
 try{
  var agecheck=prompt("This movie is rated PG-13. Please enter your age before continuing:")
  if (isNaN(parseInt(agecheck)))
   throw new SyntaxError("Please enter a valid age")
  else if (agecheck<13)
   throw new RangeError("Sorry, but you are too young for this movie")
  alert("Enjoy the movie!")
 }
 catch(e){
  alert(e.name+" "+e.message)
 }
}

This has the effect of changing what e.name returns- SyntaxError and RangeError, respectively. If that's not enough, you can even throw a generic Error object with custom name and message properties:

throw{
 name: "JavaScriptKit Error",
 message: "Error detected. Please contact webmaster"
}

And with that we throw in the towel!

번호 제목 글쓴이 날짜 조회 수
246 [Gemini] ajax 와 fetch 의 차이 황제낙엽 2025.01.04 3419
245 [검토 완료] 디바이스 카메라로 촬영한 사진을 서버에 업로드하기 샘플 황제낙엽 2024.11.21 3987
244 브라우저에서 이미지를 편집(crop 등) 할 수 있는 오픈소스 Cropper.js 황제낙엽 2024.11.16 3842
243 [ChatGPT] json data 의 정렬 [1] 황제낙엽 2024.07.23 3352
242 DOMContentLoaded 이벤트와 window.onload 이벤트 황제낙엽 2024.07.15 3669
241 fetch() 사용 예제들 황제낙엽 2024.07.09 3380
240 [Copilot] Vanilla JavaScript에서 외부 스크립트 파일에 정의된 함수들을 로드 황제낙엽 2024.06.21 3758
239 [Copilot] ES6 모듈(module) 문법 황제낙엽 2024.06.21 3805
238 [Copilot] JSON 객체 내부 데이터를 순회하면서 조회하는 코드 황제낙엽 2024.06.02 3270
237 [Copilot] JavaScript로 서버에 특정 값을 POST 방식으로 전달하고 응답을 기다리지 않고 바로 종료 황제낙엽 2024.05.31 3615
236 json 데이터 내의 변수명에 prefix 로 type 표현하기 황제낙엽 2024.04.15 3361
235 fetch() 함수 사용 예제 file 황제낙엽 2023.11.23 3605
234 현재 document 의 host 와 port 를 얻는 방법 황제낙엽 2023.10.03 4209
233 (Bard) FileReader 로 여러개의 파일을 read 하는 법 file 황제낙엽 2023.08.23 3660
232 How to build a file upload service with vanilla JavaScript file 황제낙엽 2023.08.22 3715
231 (Bard) JavaScript로 JSON 배열을 작성하는 방법 황제낙엽 2023.08.21 3672
230 모바일 브라우저에서 file input element 를 이용하여 여러장의 이미지를 서버에 전송하려 할때 [1] 황제낙엽 2023.08.21 3703
229 navigator.mediaDevices 황제낙엽 2023.08.21 3798
228 Barcode Detection API 황제낙엽 2023.08.06 3854
227 정규식을 이용한 이메일 검증 스크립트 file 황제낙엽 2023.06.25 2894