Saturday 29 October 2016

24. Exception Handling C# (Basic/Dasar)

Exception adalah sebuah masalah yang muncul ketika program dijalankan, ada banyak faktor yang menyebabkan terjadinya masalah tersebut. Dengan adanya masalah yang timbul tesebut perlu adanya penganganan exception tersebut.

Exception memberikan kemudahan kepada kita untuk mengatur dan menangani masalah yang muncul saat program dijalankan. Untuk menangani exceptions pada C# kita bisa menggunakan keyword try, catch, finally and throw.

  • try: adalah blok kode yang digunakan untuk melakukan pengetesan apakah pada blok kode tersebut ada masalah atau tidak. Try akan selalu diikuti dengan satu atau lebih blok catch.
  • catch: adalah blok yang digunakan untuk menangani jika pada pengetesan blok try terjadi kesalahan pada kode. Kemudian kita bisa melakukan penanganan kesalahan yang terjadi pada blok catch.
  • finally: adalah blok yang akan selalu dieksekusi setelah blok try dan catch selesai dieksekusi.
  • thrown: adalah blok yang digunakan untuk melaporkan jika terjadi kesalahan pada blok kode, blok thrown biasanya berdiri sendiri dan terpisah dari try, catch dan finally.
Syntax untuk exception handling adalah sebagai berikut:

try
{
   // statements causing exception
}
catch( ExceptionName e1 )
{
   // error handling code
}
catch( ExceptionName e2 )
{
   // error handling code
}
catch( ExceptionName eN )
{
   // error handling code
}
finally
{
   // statements to be executed
}

Berdasarkan syntax diatas kita bisa menangani kesalahan berdasarkan exception yang berbeda beda menggunakan multiple catch.

Exception Classes pada C#

Pada C# exception akan ditangani oleh class System.Exception, System.ApplicationException dan System.SystemException.

Tabel berikut ini adalah beberapa class untuk menangani exception pada C#

Exception ClassDescription
System.IO.IOExceptionHandles I/O errors.
System.IndexOutOfRangeExceptionHandles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchExceptionHandles errors generated when type is mismatched with the array type.
System.NullReferenceExceptionHandles errors generated from deferencing a null object.
System.DivideByZeroExceptionHandles errors generated from dividing a dividend with zero.
System.InvalidCastExceptionHandles errors generated during typecasting.
System.OutOfMemoryExceptionHandles errors generated from insufficient free memory.
System.StackOverflowExceptionHandles errors generated from stack overflow.
Menangani Exception

Untuk mengani exception kita bisa menggunakan try, catch dan finally blok. Yang paling penting adalah penggunaan try - catch blok sedangkan untuk finally blok adalah optional.

Berikut ini adalah contoh program untuk mengiliustrasikan penanganan exception:

using System;
namespace ErrorHandlingApplication
{
   class DivNumbers
   {
      int result;
      DivNumbers()
      {
         result = 0;
      }
      public void division(int num1, int num2)
      {
         try
         {
            result = num1 / num2;
         }
         catch (DivideByZeroException e)
         {
            Console.WriteLine("Exception caught: {0}", e);
         }
         finally
         {
            Console.WriteLine("Result: {0}", result);
         }
      }
      static void Main(string[] args)
      {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}

Contoh di atas adalah untuk mengani kesalah jika terjadi pembagian dengan 0, setelah program dijalankan maka akan memberikan keluaran sebagai berikut:

Exception caught: System.DivideByZeroException: Attempted to divide by zero. 
at ...
Result: 0

Kita juga bisa mendefinisikan exception kita sendiri, Untuk membuat exception kita bisa menggunakan class Exception. Contoh program dibawah ini akan mengilustrasikan bagaimana custom exception dibuat:

using System;
namespace UserDefinedException
{
   class TestTemperature
   {
      static void Main(string[] args)
      {
         Temperature temp = new Temperature();
         try
         {
            temp.showTemp();
         }
         catch(TempIsZeroException e)
         {
            Console.WriteLine("TempIsZeroException: {0}", e.Message);
         }
         Console.ReadKey();
      }
   }
}

public class TempIsZeroException: Exception
{
   public TempIsZeroException(string message): base(message)
   {
   }
}

public class Temperature
{
   int temperature = 0;
   public void showTemp()
   {
      if(temperature == 0)
      {
         throw (new TempIsZeroException("Zero Temperature found"));
      }
      else
      {
         Console.WriteLine("Temperature: {0}", temperature);
      }
   }
}

Contoh program diatas akan melakukan pengecekan jika nilai temperature bernilai 0 maka akan mengahsilkan TemperatureException.

Setelah program dijalankan akan memberikan output sebagai berikut:

TempIsZeroException: Zero Temperature found

Ok guys, sampai disini dulu dan sampai ketemu di tutorial selanjutnya File/IO.

12 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.


    rpa training in chennai | best rpa training in chennai | rpa training in chennai| rpa training in bangalore
    rpa training in pune| rpa online training

    ReplyDelete
  4. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.

    Data Science training in Chennai | Data science training in bangalore
    Data science training in pune| Data science online training
    Python training in Kalyan nagar

    ReplyDelete
  5. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post.is article.
    java training in chennai | java training in bangalore

    java online training | java training in pune

    ReplyDelete
  6. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    python training in tambaram | python training in annanagar | python training in jayanagar

    ReplyDelete
  7. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.

    Oracle Training in Chennai | Best Oracle Training Institute in Chennai
    Web Design Training in Chennai
    Web Design Training in Chennai|Best Web Design Training in Chennai

    ReplyDelete
  8. I am really very happy to find this particular site. I just wanted to say thank you for this huge read!! I absolutely enjoying every petite bit of it and I have you bookmarked to test out new substance you post.thanks lot!!

    android training in chennai

    android online training in chennai

    android training in bangalore

    android training in hyderabad

    android Training in coimbatore

    android training

    android online training


    ReplyDelete
  9. You actually make it look so easy with your performance but I find this matter to be actually something which I think I would never comprehend. It seems too complicated and extremely broad for me.
    I'm looking forward for your next post, I’ll try to get the hang of it!
    business analytics course in hyderabad

    ReplyDelete