精通ASP.NET(基于VB.NET)( 三)VB.NET异常处理
(1)结构化异常处理::
try
...........
catch
............
flnally
................
end try
其中Catch的结构有三种:Catch、Catch...As 和 Catch...When。其中Catch...As 和 Catch...When 子句捕捉特定的异常,并允许相关的语句块指定应用程序如何处理。
例:(登录界面部分代码)
Dim sqlconn as New sqlcliet.sqlconnection(configurationsettings.appsettings("connectionstring"))
Dim select_string as string="select * from user where user_name='" & trim(user_name.text) & "' and user_pwd='" & trim(user_pwd.text) & "' "
Dim select_comm as New sqlclient.sqlcommand(select_string,sqlconn)
Dim select_reader as sqlclient.sqldatareader
try
sqlconn.open()
select_reader=selec_comm.executereader(commandbehaviorcloseconnection)
if select_reader.read()=true then
dim username as string
session("username")=trim(user_name.text)
response.redirect("mian.aspx")
select_reader.close()
sqlconn.close()
else
response.write("<script langusge='javascript' runat='server'>window.alert('用户名或密码错误错误!')</script>")
end if
catch sqlexc as execption
response.write("错误发生!"&sqlexc.tostring())
finally
if not select_reader is nothing then
select_reader.close()
end if
(2)非结构化异常处理:通过Error对象及On Error、Resume和Error三种语句实现。
例:
On Error Resume Next
Err.Clear
Err.Raise(33333)
Err.Description = "您没有输入数字!"
MsgBox(Err.Number)
MsgBox(Err.Description)