ErrorHandling [JavaScript Tutorials] Error handling in JavaScript using try/catch/finally - The Error object and throwing your own errors (해석중)
sitelink1 | |
---|---|
sitelink2 | |
sitelink3 | |
sitelink4 | http://1 |
extra_vars4 | ko |
extra_vars5 | http://The Error object and throwing your own errors |
extra_vars6 | sitelink1 |
The |
Error Name | Description |
---|---|
EvalError | An error in the eval() function has occurred. |
RangeError | Out of range number value has occurred. |
ReferenceError | An illegal reference has occurred. |
SyntaxError | A 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. |
TypeError | An error in the expected variable type has occurred. |
URIError | An 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)
}
}
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!
댓글 0
번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|
117 | CORS 관련 레퍼런스 URL | 황제낙엽 | 2020.07.10 | 53 |
116 | Navigator 객체란? | 황제낙엽 | 2011.02.22 | 53 |
115 | Function.apply() 와 Function.call() | 황제낙엽 | 2011.10.07 | 51 |
114 | JavaScript 재입문 | 황제낙엽 | 2012.05.29 | 50 |
113 | insertAdjacentHTML Method | 황제낙엽 | 2005.12.19 | 50 |
112 | ECMA 스크립트의 JSON | 황제낙엽 | 2019.10.16 | 48 |
111 | String 에 trim() 함수 적용하기 | 황제낙엽 | 2011.08.28 | 48 |
110 | 3시간 걸려서 만든 입력폼 자릿수체크 스크립트 | 황제낙엽 | 2006.04.22 | 48 |
109 | 멤버 연산자 | 황제낙엽 | 2014.12.30 | 47 |
108 | 연산자 (===, ==, >=, <=) | 황제낙엽 | 2012.05.30 | 47 |
107 | [key:value] 형태로 object를 저장할 수 있는 Static영역의 해쉬맵 클래스 (Map) | 황제낙엽 | 2008.11.04 | 46 |
106 | Dynatrace For Ajax Performance | 황제낙엽 | 2010.08.18 | 45 |
105 | CORS(Cross-Origin Resource Sharing) - 3 | 황제낙엽 | 2017.03.07 | 45 |
104 | 폼으로 XML 데이터 전송 (JSP+Javascript) | 황제낙엽 | 2005.12.04 | 43 |
103 | delete 연산자에 대한 고찰 | 황제낙엽 | 2012.06.11 | 42 |
102 | object clone | 황제낙엽 | 2011.07.08 | 41 |
101 | User Agent 관련 Reference URL | 황제낙엽 | 2011.02.22 | 41 |
100 | 잘못된 종속관계 해지에 따른 메모리 누수 예제 | 황제낙엽 | 2009.04.03 | 41 |
99 | [펌] 아사페릴의 사생활 - prototype과 __proto__ 와 constructor | 황제낙엽 | 2009.04.02 | 41 |
98 | withCredentials 관련 | 황제낙엽 | 2020.07.29 | 39 |