The type initializer for threw an exception
TypeInitializationExceptionUnderstand the TypeInitializationException, which indicates a static constructor error.
This page was last reviewed on Sep 11, 2023.
TypeInitializationException. This occurs when a static constructor has an error. It is thrown from static constructors. It wraps the errors from static constructors.
A warning. This exception cannot be reliably trapped outside of the static constructor. It can be useful when investigating errors in static constructors.
This program shows that this exception is raised when any exception is thrown inside a type initializer, also called a static constructor.
Info The runtime wraps any exception raised in the static constructor inside a TypeInitializationException.
And The InnerException is the original cause of the problem. The TypeInitializationException is only raised from type initializers.
Unhandled Exception: System.TypeInitializationException: The type initializer for ‘Program’ threw an exception. —> System.DivideByZeroException: Attempted to divide by zero. at Program..cctor. — End of inner exception stack trace — at Program.Main()
Notes, program. When Main is reached, the static Program constructor is executed. The code in the static constructor attempts to divide by zero.
And This causes a DivideByZeroException to be thrown. The runtime then wraps this exception inside a TypeInitializationException.
Fix. To fix this error, you can add try-catch blocks around the body of the static constructor that throws it. Alternatively, you could avoid the exception with an if-statement.
A summary. TypeInitializationException is used to wrap exceptions inside type initializers, also called static constructors. This is a special-purpose exception.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
Type Initialization Exception Class
Namespace: System Assembly: System.Runtime.dll Assembly: mscorlib.dll Assembly: netstandard.dll Source: TypeInitializationException.cs Source: TypeInitializationException.cs Source: TypeInitializationException.cs
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
The exception that is thrown as a wrapper around the exception thrown by the class initializer. This class cannot be inherited.
public ref class TypeInitializationException sealed : Exception
public ref class TypeInitializationException sealed : SystemException
public sealed class TypeInitializationException : Exception
public sealed class TypeInitializationException : SystemException
[System.Serializable] public sealed class TypeInitializationException : SystemException
[System.Serializable] [System.Runtime.InteropServices.ComVisible(true)] public sealed class TypeInitializationException : SystemException
type TypeInitializationException = class inherit Exception
type TypeInitializationException = class inherit SystemException
[] type TypeInitializationException = class inherit SystemException
[] [] type TypeInitializationException = class inherit SystemException
Public NotInheritable Class TypeInitializationException Inherits Exception
Public NotInheritable Class TypeInitializationException Inherits SystemException
System.TypeInitializationException: ‘The type initializer for ‘ScheduleDataProcessor.Logger’ threw an exception.’
Dear Sir,
i am getting following exception
System.TypeInitializationException: ‘The type initializer for ‘ScheduleDataProcessor.Logger’ threw an exception.’
inner exception NotSupportedException: The given path’s format is not supported.
please find the following code:
namespace ScheduleDataProcessor
public partial class DataProcessor : Form
<
private System.Timers.Timer timer = new System.Timers.Timer();
DBConnection dbConnection = new DBConnection();
string pathBackup = ((object)ConfigurationManager.AppSettings[«DATABACKUP»]).ToString();
public DataProcessor()
<
InitializeComponent();
>
private void btnStartStop_Click(object sender, EventArgs e) < this.timer.Elapsed += new ElapsedEventHandler(this.OnElapsed); this.timer.Interval = (double)Convert.ToInt64(((object)ConfigurationManager.AppSettings["Interval"]).ToString()); this.timer.Enabled = true; >private void OnElapsed(object sender, ElapsedEventArgs e) < this.timer.Enabled = false; Logger.Append("Service is recalled"); //**<-----**--getting exception here**** try < this.LoopDataDirectory(); >catch (Exception ex) < Logger.Append(ex.Message.ToString()); >finally < this.timer.Enabled = true; >>
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
Saved searches
Use saved searches to filter your results more quickly
Cancel Create saved search
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
xunit / xunit Public
«System.TypeInitializationException : The type initializer for » threw an exception» when Realm Database NuGet Package is installed #2361
HobDev asked this question in Question
Aug 9, 2021 · 2 comments · 1 reply
Something went wrong.
Quote reply
>’s edit
<> deleted this content .
>’s edit
Something went wrong.
Aug 9, 2021
I am working on Xamarin.Forms project. I have a xUnit test project targeting dotnetcore 3.1. When I run the tests I get the error mentioned in the title. : The complete test detail summary is as follows:
Milk.UnitTests.LoginTest.SelectedLanguageApplied(language: «Hindi»)
Source: LoginTests.cs line 22
Duration: < 1 msMessage:
System.TypeInitializationException : The type initializer for » threw an exception.
—- System.InvalidProgramException : The JIT compiler encountered invalid IL code or an internal limitation.Stack Trace:
LoginTest.SelectedLanguageApplied(String language)
AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
LoginTest.SelectedLanguageApplied(String language)
—— Inner Stack Trace ——
cctor()
The test method is:
[Theory] [InlineData("Hindi")] [InlineData("English")] //The choosen language is applied public async void SelectedLanguageApplied(string language) < //Arrange LoginViewModel loginViewModel = new LoginViewModel(); //Act string result = await loginViewModel.ChangeLanguage(language); //Assert Assert.Equal(language, result); >
The ViewModel method of the above test is:
public async Task ChangeLanguage(string selectedLanguage) < _selectedLanguage = selectedLanguage; CultureInfo language = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList().First(element =>element.EnglishName.Contains(selectedLanguage)); Thread.CurrentThread.CurrentUICulture = language; AppResources.Culture = language; return language.EnglishName; >
I am really frustated as the tests was running successfully before.
Thank you
Beta Was this translation helpful? Give feedback.
1 You must be logged in to vote
All reactions
The error has gone by removing the Realm Package from the Shared Project(code tested from this project). The realm package already installed in the Models project. which have all the Models of the App. The Shared project reference the Model project so it can still work with Realm.
Replies: 2 comments · 1 reply
Something went wrong.
Quote reply
bradwilson
Aug 14, 2021
Maintainer
Given the code above, I’m unable to repro your problem:
Project Sdk="Microsoft.NET.Sdk"> PropertyGroup> TargetFramework>netcoreapp3.1TargetFramework> PropertyGroup> ItemGroup> PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> PackageReference Include="xunit" Version="2.4.1" /> PackageReference Include="xunit.runner.visualstudio" Version="2.4.3"> IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitiveIncludeAssets> PrivateAssets>allPrivateAssets> PackageReference> ItemGroup> Project>
using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; public class LoginViewModel public async Taskstring> ChangeLanguage(string selectedLanguage) CultureInfo language = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList().First(element => element.EnglishName.Contains(selectedLanguage)); Thread.CurrentThread.CurrentUICulture = language; return language.EnglishName; > > public class UnitTest1 [Theory] [InlineData("Hindi")] [InlineData("English")] public async void SelectedLanguageApplied(string language) LoginViewModel loginViewModel = new LoginViewModel(); string result = await loginViewModel.ChangeLanguage(language); Assert.Equal(language, result); > >
Determining projects to restore. All projects are up-to-date for restore. xunit-2361 -> C:\Dev\repro\xunit-2361\bin\Debug\netcoreapp3.1\xunit-2361.dll Test run for C:\Dev\repro\xunit-2361\bin\Debug\netcoreapp3.1\xunit-2361.dll (.NETCoreApp,Version=v3.1) Microsoft (R) Test Execution Command Line Tool Version 16.10.0 Copyright (c) Microsoft Corporation. All rights reserved. Starting test execution, please wait. A total of 1 test files matched the specified pattern. Passed! - Failed: 0, Passed: 2, Skipped: 0, Total: 2, Duration: 2 ms - xunit-2361.dll (netcoreapp3.1)
A full repro project will be necessary.
Beta Was this translation helpful? Give feedback.