Curso de C Sharp | Excepciones en C# 1

Curso de C Sharp
Excepciones en C#

Curso de C Sharp | Excepciones en C# 2

Excepción con un catch

int i = 2;
int j = 0;
Console.WriteLine("before");
try{
        Console.WriteLine("in try");
 Console.WriteLine(i / j);
}catch (ArithmeticException e){
 Console.WriteLine("in catch");
 e.ToString();
}
Console.WriteLine("after");
Exceptions.cs

Output:

before
in the try
in catch
java.lang.ArithmeticException
after

Excepción con varios catch

int i = 2;
int j = 0;
Console.WriteLine("before");
try{
 Console.WriteLine("in try");
 Console.WriteLine(i / j);
}catch (ArithmeticException e){
 Console.WriteLine("in catch2");
 e.ToString();
}catch (Exception e){
 Console.WriteLine("in catch3");
 e.ToString();
}
      
Console.WriteLine("after");
ExceptionWithCatchs.cs

Output

before
in try
in catch2
java.lang.ArithmeticException
after

El único catch que se aplica es el que recoge la excepción. Después de este, el programa continua ejecutándose a partir del último Catch.

Para que el código compile, los tipos de Error más generales(Throwable) deben estar por debajo de los más particulares(ArithmeticException)

Throw

class ExceptionWithThrow{
 static void Main(string[] args){
  ExceptionWithThrow exceptionWithThrow = new ExceptionWithThrow();
  try{
   exceptionWithThrow.ThrowExcepcion();
  }catch (Exception e){
   Console.WriteLine("exception throwed and processed");
  }
  exceptionWithThrow.processException();
 }

 public void ThrowExcepcion() {
  throw new Exception();
 }

 public void processException(){
  try{
   throw new Exception();
  }catch (Exception e){
   Console.WriteLine("exception processes");
  }
 }
}
ExceptionWithThrow.cs

Output:

exception throwed and processed
exception processes

Finally

El finally se ejecuta siempre, se trate la excepción o no se trate la excepción. La única forma de evitar que se ejecute el finally es ejecutando un System.exit(), que mata la máquina virtual.

Se utiliza siempre en conjunción con un try-catch. No puede haber nada después del catch y antes del finally.

static void Main(string[] args){
 int i = 2;
 int j = 0;
 Console.WriteLine("before");
 try{
  Console.WriteLine(i / j);
 }catch (ArithmeticException e){
  Console.WriteLine("in catch2");
  e.ToString();
 }catch (Exception e){
  Console.WriteLine("in catch3");
 }finally{
  Console.WriteLine("in finally");
 }
 Console.WriteLine("after");
}
ExceptionWithFinally.cs

Output:

before
in catch2
java.lang.ArithmeticException
in finally
after

Ejercicio excepciones

Implementar una clase MainClass que llame al método getPrecioConIva() de la clase Servicios e imprima el valor que devuelve.

Implementar una clase Servicios con un método llamado getPrecioConIva() que recibirá un número y devolverá dicho número multiplicado por 1.16. Si el precio calculado es mayor que 100 arrojará una PrecioDemasiadoAltoException que será capturada en la MainClass.

Implementar una clase PrecioDemasiadoAltoException y sobreescribir su método message() para que imprima el texto «El precio es demasiado alto».

public override string Message{
    get {
        return "El precio es demasiado elevado.";
    }
}