The 'X' type initializer has triggered an exception

Asked

Viewed 4,074 times

2

While trying to run the line below, I get the following error message:

An Exception of type 'System.Typeinitializationexception' occurred in Programa.exe but was not handled in user code. Additional information: The 'Program.Constants' type initializer triggered an exception. If there is a Handler for this Exception, the program may be Safely continued.

var fileMoveTrash = Path.Combine(Constantes.CaixaTrash, mensagem.Name);

Where, "Constants.Caixatrash" comes from the class Constants:

static class Constantes
 {
   (...)
    public static string CaixaTrash = ConfigurationManager.AppSettings["CaixaTrashPath"];
   (...)
  }

1 answer

2


Your problem, as the exception says, is in class initialization Constantes.

Check that ConfigurationManager.AppSettings["CaixaTrashPath"] exists.

If it does not exist, an exception will be made, which if left untreated, will be transformed into a TypeInitializationException for runtime. This is because the variable could not be initialized CaixaTash.

If you have no way to guarantee that "Caixatrashpath" exists, a solution can go through defining an explicit static constructor and try to extract the value:

public static string CaixaTrash;

static Constantes()
{
    try
    {
        CaixaTrash = ConfigurationManager.AppSettings["CaixaTrashPath"];
    }
    catch(Exception ex) // E boa ideia tentar apanhar um tipo de excepcao mais especifico.
    {
        CaixaTrash = string.Empty;
        // ou
        throw new Exception("CaixaTrashPath nao encontrado")
    }
}

Note that defining a explicit static constructor will not affect other static fields you have. According to the C specification#:

If a static constructor (§10.12) exists in the class, initialization static fields occur immediately before constructor invocation static. Otherwise, the static fields initialize and run before the first static field use of this class.

This further explains why the exception is only raised when using the Path.Combine.

==Extra note==

Prefer to use static properties instead of static fields. This way ensures control over reading and writing. Reply in SOEN on the subject

  • Thank you Omni. Actually, there was another item(frequencia) in Appsettings that was not declared. Even without mentioning it, the error was raised when trying to use the 'Caixatrashpath' that existed.

  • @Santanafire as explained in the C#specification, if this other item was also a static field of Constants when used CaixaTrash for the first time, all static fields were initialized, hence the other field failed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.