A sintaxe de tratamento é a seguinte:
1 2 3 4 5 6 7 8 | try { Comandos que podem gerar exception } catch { Tratamento } |
Considere o seguinte código:
1 2 3 4 5 6 7 8 9 10 11 | using System; public class Class1 { public static void Main() { int x = 0; int y = 10; int z = y / x; Console.WriteLine(z); } } |
Podemos tratar a exception com o seguinte código:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | using System; public class Class1 { public static void Main() { int x = 0; int y = 10; try { int z = y / x; Console.WriteLine(z); } catch { Console.WriteLine("Exception disparada"); } } } |
As exceptions têm um tipo, na verdade uma classe. As nossas rotinas podem tratar um tipo e todas as classes derivadas deste tipo. Os outros são ignorados. No exemplo a seguir estamos tratando apenas um tipo de exception:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | using System; public class Class1 { public static void Main() { int x = 0; int y = 10; try { int z = y / x; Console.WriteLine(z); } catch(System.DivideByZeroException) { Console.WriteLine("Exception disparada"); } } } |
Caso desejemos manter a exception “viva”, podemos recriá-la com “throw”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | using System; public class Class1 { public static void Main() { int x = 0; int y = 10; try { int z = y / x; Console.WriteLine(z); } catch(System.DivideByZeroException) { Console.WriteLine("Exception disparada"); throw; } } } |
As exceptions são objetos que contém propriedades. Podemos acessá-los declarando um objeto ao “capturar” a exception:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | using System; public class Class1 { public static void Main() { int x = 0; int y = 10; try { int z = y / x; Console.WriteLine(z); } catch(System.DivideByZeroException E) { Console.WriteLine(“Exception disparada: “ + E.Source); } } } |