How to use Try Catch in ASP Classic

The worst part of Classic ASP in VBScript is Error Handling.

You need to type “on error resume next”, then, check, on every line, check if the previous one generates an error using [If Err.Number <> 0 then …]. That’s a real pain.

When you need solid error handling inside an ASP – VBScript sub or function, there’s a very simple method you can apply.

Just turn your existing error-handling-needed function into JavaScript, and use Try-Catch!
What? Javascript in ASP Classic?
Yes you can! It’s called JScript, it’s ECMAScript 3 compatible, and it just works.

Also, it’s totally compatible with your existing VBScript application, that will be able to call that JS method without any issue.  Even all your application VBScript variables will be shared between VB and JS.

Sample:
100% VBScript file:

<%
function fct1
	fct1 = true
	on error resume next
	' do something that can crash
	dim i : i = 1
	i = i / 0
	if err.number <> 0 then
		fct1 = false
		response.write err.number & "<br>"
		response.write err.description & "<br>"
	end if
	on error goto 0
end function

sub sub1
	dim value : value = fct1()
	response.write "result: " & value
end sub

call sub1()
%>

Now, the same, using mixed VBScript/ Javascript

<script runat="server" language="javascript"> 
function fct1(){
	try{
		// do something that can crash 
		var i = 1;
		i = parseINT(i); // <- typo
		return true;
	}
	catch(e){
		Response.Write(e.message);
		return false;
	}
}
</script>
<%
sub sub1
	dim value : value = fct1()
	response.write value
end sub

call sub1()
%>

Now, go and start converting your Classic ASP functions in JavaScript!
Just, watch out as JScript is case sensitive, VBScript is not.
vb: response.write "txt"
js: Response.Write("txt");

 

2 thoughts on “How to use Try Catch in ASP Classic”

  1. Thanks for this. Still have a couple of old asp classic apps I maintain. Always handy to have some useful tips. Especially JS and IIS based to help while I move them over to something new.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.