The type initializer of 'X' triggered an exception

2

When I try to run the line below, I get the following error message:

An exception of type 'System.TypeInitializationException' occurred in Program.exe but was not handled in user code.      Additional information: The initializer of type 'Program.Constants' has thrown an exception. If there is a handler for this exception, the program may be continued.

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

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

static class Constantes
 {
   (...)
    public static string CaixaTrash = ConfigurationManager.AppSettings["CaixaTrashPath"];
   (...)
  }
    
asked by anonymous 06.11.2014 / 21:56

1 answer

2

Your problem, as the exception says, is at the start of class Constantes .

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

If it does not exist, an exception will be generated, which, if untreated, will be transformed into an exception of type TypeInitializationException by runtime . This is because the variable CaixaTash could not be initialized.

If you can not guarantee that "BoxTrashPath" exists, a workaround may be to define 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 setting an explicit static constructor will not affect other static fields that you have. According to the C # specification:

  

If a static constructor (§10.12) exists in the class, initialization   of static fields occurs immediately before invocation of the constructor   static. Otherwise, the initialization of the static fields is performed before the   first static field use of this class.

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

== Extra note ==

Prefer to use static properties rather than static fields. This ensures control over reading and writing. SOEN Response on the Subject

    
07.11.2014 / 11:15