VBの例外処理について!

Posted in VB

どうも、お久しぶりのisamです。

今日は今仕事でやっているVBのお話です。
今までPHPとかPerlで例外処理とかあんましていないんですが(やれよっ!)、VBをやるようになって
かなり使うので自分用にメモ。

ファイルを開く時にファイルがない場合やメモリ不足の時には例外がスローされます。

ファイルがない場合はFileNotFoundException
メモリ不足の場合はOutOfMemoryException
それ意外に例外にもありますが、割愛します。

これらの例外を捕捉するために
Try~Catch~Finally~End Try
Try~Using~End Using~Catch~End Try
構文を使います。

まずTry~Catch~Finally~End Tryの例

Imports System
Imports System.IO
Imports System.Text

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles Button1.Click
        Dim path As String = "C:\str.txt"
        Dim sr As StreamReader
        Dim fb As Boolean = True

        Try
            sr = New StreamReader(path, Encoding.GetEncoding("Shift_JIS"))
            MsgBox(sr.ReadToEnd())
        Catch ex As FileNotFoundException
            MsgBox(ex.Message)
            '例外が発生したのでFalseを代入してFinallyブロックの処理を飛ばす
            'NullReferenceExceptionを発生させないため(Streamをオープンする事ができていないため)
            fb = False
        Catch ex As OutOfMemoryException
            MsgBox(ex.Message)
            '明示的にメモリ開放
            GC.Collect()
        Catch ex As Exception
            'それ以外
            MsgBox(ex.Message)
        Finally
           'Streamが開いていれば閉じるように分岐
           '※Fainallyブロックはどんな時でもTry構文のあとに必ず実行される
            If fb = True Then
               'Streamを閉じる
                sr.Close()
            End If
        End Try
    End Sub
End Class

この場合、IDE上だとNull参照の警告がでますが、Finallyブロックの部分さえちゃんとすれば例外は発生しません。

Try~Using~End Using~Catch~End Tryの場合

Imports System
Imports System.IO
Imports System.Text

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles Button2.Click
        Dim path As String = "C:\test.txt"

        Try
            Using sr = New StreamReader(path, Encoding.GetEncoding("Shift_JIS"))
                MsgBox(sr.ReadToEnd())
            End Using
        Catch ex As FileNotFoundException
            MsgBox(ex.Message)
        Catch ex As OutOfMemoryException
            MsgBox(ex.Message)
            GC.Collect()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class

この場合はUsing構文が自動的にDisposeメソッドを呼び出すので明示的に
Closeメソッドを書いたりIf文で分岐する必要がありません。
簡潔に書けるのでとても便利ですね。

最近WEB系のスクリプトを書いていないのでそろそろ書かないと忘れてしまう。。。orz

ではまた!

Posted by isam   @   23 2月 2010
Tags :

Like this post? Share it!

RSS Digg Twitter StumbleUpon Delicious Technorati

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

Previous Post
«
Next Post
»
Powered by Wordpress   |   Lunated designed by ZenVerse