sitelink1 | |
---|---|
sitelink2 | |
sitelink3 | |
sitelink4 | http://1 |
extra_vars4 | ko |
extra_vars5 | http://www.javascriptkit.com/javatutors/trycatch.shtml |
extra_vars6 | sitelink1 |
Error handling, like many aspects of JavaScript, has been maturing since the dark ages of Netscape and IE4. No longer are you forced to settle for what the browser throws in your face in an event of a JavaScript error, but instead can take the matter into your own hands. The try/catch/finally
statement of JavaScript lets you dip your toes into error prune territory and "reroute" when a JavaScript "exception" is encountered. Along with other defensive coding techniques such as Object detection and the onError event, try/catch/finally
adds the ability to navigate around certain errors that in the past would have instantly stopped your script at its tracks. No more!
try/catch/finally
try/catch/finally
are so called exception handling statements in JavaScript. An exception is an error that occurs at runtime due to an illegal operation during execution. Examples of exceptions include trying to reference an undefined variable, or calling a non existent method. This versus syntax errors, which are errors that occur when there is a problem with your JavaScript syntax. Consider the following examples of syntax errors versus exceptions:
alert("I am missing a closing parenthesis //syntax error
alert(x) //exception assuming "x" isn't defined yet
undefinedfunction() //exception
try/catch/finally
lets you deal with exceptions gracefully. It does not catch syntax errors, however (for those, you need to use the onerror event). Normally whenever the browser runs into an exception somewhere in a JavaScript code, it displays an error message to the user while aborting the execution of the remaining code. You can put a lid on this behaviour and handle the error the way you see fit using try/catch/finally
. At its simplest you'd just use try/catch
to try and run some code, and in the event of any exceptions, suppress them:
try{
undefinedfunction()
}
catch(e){
//catch and just suppress error
}
Assuming undefinedfunction()
is undefined, when the browser runs the above, no errors will be shown. The syntax for try/catch/finally
is a try
clause followed by either a catch
or finally
clause (at least one or both of them). The catch
clause if defined traps any errors that has occurred from try
, and is indirectly passed the error object that contains additional info about the error. Lets see a slightly more complex example now:
try{
undefinedfunction()
alert('I guess you do exist')
}
catch(e){
alert('An error has occurred: '+e.message)
}
Click on the above button, and notice how only "An Error has occurred" alert pops up, but not "I guess you do exist". This tells us that when try
encounters an error, it immediately skips any remaining code inside it and goes straight to catch
. The default error message is obviously suppressed, though you can still retrieve this information by accessing the Error object that gets indirectly passed into catch
. We'll look at the Error object in detail on the next page.
There's another clause, finally
, that if defined will be executed regardless of whether an error occurs in the try
clause proceeding it:
try{
undefinedfunction()
alert('I guess you do exist')
}
catch(e){
alert('An error has occurred: '+e.message)
}
finally{
alert('I am alerted regardless of the outcome above')
}
finally
can be useful when you need to "clean up" after some code inside try
. While it's true finally
will always be executed if defined, certain statements inside try such as continue
, break
, return
, or when an error has occurred and there is no catch
clause will all cause finally
to be executed immediately thereafter. In the following example, the value "5" is alerted, since control is handed over to finally
when i reaches 5 inside try:
try{
for (var i=0; i<10; i++){
if (i==5)
break
x=i
}
}
finally{
alert(i) //alerts 5
}
Nested try/catch/finally statements
As a reminder, try
should never be defined just by itself, but always followed by either catch
, finally
, or both. Within each clause, you can define additional try/catch/finally
statements following the same aforementioned rule. Take the instance where an error has occurred within the catch
clause- defining an additional try/catch
statement inside it takes care of it:
var ajaxrequest=null
if (window.ActiveXObject){ //Test for support for different versions of ActiveXObject in IE
try {
ajaxrequest=new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
ajaxrequest=new ActiveXObject("Microsoft.XMLHTTP")
} //end inner try
catch (e){
alert("I give up. Your IE doesn't support Ajax!")
} //end inner catch
} //end outer catch
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
ajaxrequest=new XMLHttpRequest()
ajaxrequest.open('GET', 'process.php', true) //do something with request
Here I'm using a nested try/catch
statement to try and determine in IE which version of the ActiveX Object it supports that's needed to initialize an Ajax request. Using object detection won't work here, since the issue isn't whether the browser supports ActiveXObject
here, but which version.
댓글 0
번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|
117 | User Agent 관련 Reference URL | 황제낙엽 | 2011.02.22 | 41 |
116 | 각 브라우저 별 User Agent 정보 | 황제낙엽 | 2011.02.22 | 823 |
115 | History of User Agent | 황제낙엽 | 2011.02.22 | 38 |
114 | Navigator 객체란? | 황제낙엽 | 2011.02.22 | 53 |
113 | Understanding User-Agent Strings | 황제낙엽 | 2011.02.22 | 76 |
112 | User Agent 정보 모음 | 황제낙엽 | 2011.02.22 | 7768 |
111 | ActiveX 설치 여부를 검사하는 스크립트 | 황제낙엽 | 2011.02.13 | 4053 |
110 | 자바스크립트 예약어 | 황제낙엽 | 2010.11.03 | 35 |
109 | YUI Logger(Yahoo) 를 동적으로 로드하는 북마크릿 | 황제낙엽 | 2010.10.03 | 25 |
108 | Javascript 를 사용하여 Binary File 읽기 | 황제낙엽 | 2010.09.29 | 500 |
107 | 크로스 브라우저를 위한 브라우저 검사 코드 | 황제낙엽 | 2010.08.27 | 86 |
106 | Dynatrace For Ajax Performance | 황제낙엽 | 2010.08.18 | 45 |
105 | javascirpt IME-Mode 설정하기 | 황제낙엽 | 2010.08.17 | 1112 |
104 | Iframe 내의 페이지 접근방법 | 황제낙엽 | 2009.11.12 | 59 |
103 | 외부 라이브러리 (.js) 의 바람직한 동적 로딩 (The best way to load external JavaScript) | 황제낙엽 | 2009.10.05 | 124 |
102 | 숫자값으로의 변환 형태 | 황제낙엽 | 2009.09.02 | 18 |
101 | Boolean 데이터 타입 | 황제낙엽 | 2009.09.02 | 16 |
100 | toString 변환 테이블 | 황제낙엽 | 2009.09.02 | 13 |
99 | URI 인코딩을 해야 하는 문자들 | 황제낙엽 | 2009.09.02 | 23 |
98 | 체인 생성자(생성자 체인), 프로토타입 체인 그리고 생성자 재지정 | 황제낙엽 | 2009.08.12 | 55 |