Bagaimana caranya membuat sebuah exception yang messagenya kita buat sendiri? ada beberapa cara untuk membuat hal tersebut, yaitu dengan langsung menggunakan throw exception didalam blok exception yang digunakan atau dengan membuat sebuah class yang inherits dari class ApplicationException atau inherits dari class System.Data.SqlTypes.SqlTypeException kalau kita ingin mengkostumisasi message error dari SqlException.
Tiap-tiap message yang di generate bisa ditentukan dengan properti Class dari variable exceptionnya untuk menentukan Severity Level Errornya, setelah itu baru bisa kita buat custom messagenya dengan bahasa indonesia. Berikut contoh codenya untuk VB.NET dan C#...Asumsi error yang digenerate yaitu untuk Severity Level Error 16 yang mempunyai message “Invalid Object Name“ (contoh disini dibuat dengan menuliskan nama Table yang salah pada database Northwind)..
1: using System;
2: using System.Collections.Generic;
3: using System.ComponentModel;
4: using System.Data;
5: using System.Drawing;
6: using System.Text;
7: using System.Windows.Forms;
8: using System.Data.SqlClient;
9:
10: namespace TheCustomException
11: {
12: public partial class Form1 : Form
13: {
14: public Form1()
15: {
16: InitializeComponent();
17: }
18:
19: private void button1_Click(object sender, EventArgs e)
20: {
21: SqlDataAdapter da;
22: DataSet ds;
23: try
24: {
25: da = new SqlDataAdapter(
26: "Select * From Customer",
27: "Database=Northwind;Server=localhost;" +
28: "Integrated Security=SSPI");
29: ds = new DataSet();
30: da.Fill(ds, "cust");
31: }
32: catch (SqlException ex)
33: {
34: if (ex.Class == 16)
35: {
36: MySqlException myEx = new MySqlException();
37: MessageBox.Show(myEx.Message.ToString());
38: }
39: }
40: }
41: }
42:
43: public class MySqlException :
44: System.Data.SqlTypes.SqlTypeException
45: {
46: public MySqlException()
47: : base("Nama object tidak dikenal")
48: {
49: }
50: }
51: }
VB.NET
1: Imports System.Data.SqlClient
2:
3: Public Class Form1
4: Inherits System.Windows.Forms.Form
5:
6: Private Sub Button1_Click(ByVal sender As System.Object, _
7: ByVal e As System.EventArgs) Handles Button1.Click
8: Dim da As SqlDataAdapter
9: Dim ds As DataSet
10: Try
11: da = New SqlDataAdapter( _
12: "Select * From Customer", _
13: "Database=Northwind;Server=localhost;" & _
14: "Integrated Security=SSPI")
15: ds = New DataSet
16: da.Fill(ds, "cust")
17: Catch ex As SqlException
18: If ex.Class = 16 Then
19: Dim ex2 As New MySqlException
20: MsgBox(ex2.Message)
21: End If
22: End Try
23: End Sub
24: End Class
25:
26: Public Class MySqlException
27: Inherits System.Data.SqlTypes.SqlTypeException
28:
29: Public Sub New()
30: MyBase.New("Nama object tidak dikenal")
31: End Sub
32: End Class