public void ConstructorWithMessageWorks() { var ex = new DivideByZeroException("The message"); Assert.True((object)ex is DivideByZeroException, "is DivideByZeroException"); Assert.AreEqual(ex.InnerException, null, "InnerException"); Assert.AreEqual(ex.Message, "The message"); }
public void DefaultConstructorWorks() { var ex = new DivideByZeroException(); Assert.True((object)ex is DivideByZeroException, "is DivideByZeroException"); Assert.AreEqual(ex.InnerException, null, "InnerException"); Assert.AreEqual(ex.Message, "Division by 0."); }
public static void Convert_Exception_To_XML() { DivideByZeroException outerException = new DivideByZeroException(); ExceptionXElement xmlRaw; { try { var path = File.ReadAllLines("file does not exist"); } catch (Exception ex) { outerException = new DivideByZeroException("Outer exception", ex); } xmlRaw = new ExceptionXElement(outerException); } var xml = xmlRaw.ToString(); Assert.IsTrue(xml.ToLower().Contains("exception")); // TODO: Comment this in once .NET Core 1.1 is released. // Assert.IsTrue(xml.ToLower().Contains("DivideByZeroException")); Assert.IsTrue(xml.Contains("<")); Assert.IsTrue(xml.Contains(">")); }
public void DivisionByZero() { var divideByZeroException = new DivideByZeroException(); AssertExpressionError(divideByZeroException.Message, 5, "20px / 0"); AssertExpressionError(divideByZeroException.Message, 14, "1 + 2 - 3 * 4 / 0"); AssertExpressionError(divideByZeroException.Message, 6, "1 + 2 / 0 - 3 * 4 / 0"); }
public void ErrorWithException() { var ex = new DivideByZeroException(); var guid1 = Guid.NewGuid(); Log.Error(ex, "guid1: {0}", guid1); AssertLatestLogEntry("[ERROR] guid1: " + guid1 + ": System.DivideByZeroException: Attempted to divide by zero."); }
public void Error_WhenErrorWithExceptionLogged_ShouldLogErrorWithException() { var ex = new DivideByZeroException(); var expectedGuid = Guid.NewGuid(); _logger.Error(ex, "guid: {0}", expectedGuid); AssertLatestLogEntryEqualsExpectedLogEntry(String.Format("ERROR|{0}|guid: {1}", s_loggerName, expectedGuid)); }
public void TypePropertiesAreCorrect() { Assert.AreEqual(typeof(DivideByZeroException).GetClassName(), "Bridge.DivideByZeroException", "Name"); object d = new DivideByZeroException(); Assert.True(d is DivideByZeroException, "is DivideByZeroException"); Assert.True(d is Exception, "is Exception"); }
public void ConstructorWithMessageAndInnerExceptionWorks() { var inner = new Exception("a"); var ex = new DivideByZeroException("The message", inner); Assert.IsTrue((object)ex is DivideByZeroException, "is DivideByZeroException"); Assert.IsTrue(ReferenceEquals(ex.InnerException, inner), "InnerException"); Assert.AreEqual(ex.Message, "The message"); }
public void ConstructorResolving_UsingIsExpressionCastingForBaseConstructor_ReturnsProxiedInstanceWithCastedType() { var exception = new DivideByZeroException(); var ctor = GetConstructorByType<DerivedClass>(typeof(Exception)); var func = ExecuteConstructorLambda<Func<Exception, DerivedClass>>(ctor); var derivedClass = func(exception); var result = (bool)derivedClass.BaseValue; Assert.IsFalse(result); }
public void read_normal_exception() { var record = new JobExecutionRecord(); var ex = new DivideByZeroException("Only Chuck Norris can do that"); record.ReadException(ex); record.ExceptionText.ShouldBe(ex.ToString()); }
public void ShouldTrackExceptionsAsFailureReasons() { var exceptionA = new InvalidOperationException(); var exceptionB = new DivideByZeroException(); execution.Exceptions.ShouldBeEmpty(); execution.Fail(exceptionA); execution.Fail(exceptionB); execution.Exceptions.ShouldEqual(exceptionA, exceptionB); }
public void creates_the_grammar_error() { var ex = new DivideByZeroException("No!"); var fixture = new InvalidFixture(typeof (FixtureThatBlowsUp), ex); var model = fixture.Compile(null); var error = model.errors.Single(); error.error.ShouldBe(ex.ToString()); error.message.ShouldBe("Fixture StoryTeller.Testing.FixtureThatBlowsUp could not be loaded"); }
public void TypePropertiesAreCorrect() { Assert.AreEqual(typeof(DivideByZeroException).FullName, "ss.DivideByZeroException", "Name"); Assert.IsTrue(typeof(DivideByZeroException).IsClass, "IsClass"); Assert.AreEqual(typeof(DivideByZeroException).BaseType, typeof(Exception), "BaseType"); object d = new DivideByZeroException(); Assert.IsTrue(d is DivideByZeroException, "is DivideByZeroException"); Assert.IsTrue(d is Exception, "is Exception"); var interfaces = typeof(DivideByZeroException).GetInterfaces(); Assert.AreEqual(interfaces.Length, 0, "Interfaces length"); }
public void exceptions_are_critical() { var context = SpecContext.ForTesting(); var ex = new DivideByZeroException(); var section = new Section("Math") { id = "5" }; var action = SilentAction.AsCritical("Fixture", Stage.teardown, x => { throw ex; }, section); action.Execute(context); ShouldBeTestExtensions.ShouldBe(context.CanContinue(), false); }
internal static object Divide(uint lhs, uint rhs) { if (rhs == 0) { DivideByZeroException innerException = new DivideByZeroException(); throw new RuntimeException(innerException.Message, innerException); } if ((lhs % rhs) == 0) { return (lhs / rhs); } return (((double) lhs) / ((double) rhs)); }
internal static object Divide(long lhs, long rhs) { if (rhs == 0L) { DivideByZeroException innerException = new DivideByZeroException(); throw new RuntimeException(innerException.Message, innerException); } if (((lhs != -9223372036854775808L) || (rhs != -1L)) && ((lhs % rhs) == 0L)) { return (lhs / rhs); } return (((double) lhs) / ((double) rhs)); }
// do the division if legal public double DoDivide(double a, double b) { if (b == 0) { DivideByZeroException e = new DivideByZeroException(); e.HelpLink = "http://www.libertyassociates.com"; throw e; } if (a == 0) { throw new ArithmeticException(); } return a / b; }
// do the division if legal public double DoDivide(double a, double b) { if (b == 0) { DivideByZeroException e = new DivideByZeroException(); e.HelpLink = "http://www.libertyassociates.com"; throw e; } if (a == 0) { // create a custom exception instance MyCustomException e = new MyCustomException("Can't have zero dividend"); e.HelpLink = "http://www.libertyassociates.com/NoZeroDividend.htm"; throw e; } return a / b; }
//returns message as per HW0. Addressee is currently not used for anything public bool SendAlert(string Addressee, string Message) { if (beenDisposed_) throw new ObjectDisposedException("Communicator has been disposed."); if (Addressee.Length>=1 && Addressee.Substring(0, 1) == "A") {throw new SecureCommunicationException("Addressee Starts with invalid charicter: A"); } if (Addressee.Length>=1 && Addressee.Substring(0,1)== "B") { int zero = 0; int bad = 1 / zero;}//divide by 0 if (Addressee.Length >= 1 && Addressee.Substring(0, 1) == "C") { try{ int zero = 0; int bad = 1 / zero;//divide by 0 } catch (System.DivideByZeroException){ DivideByZeroException e = new DivideByZeroException(); throw new SecureCommunicationException(Addressee, "Tried to divide by Zero", e); } } //added for HW4 to queue alert to AlertPool try { //fetch a mutex and use it to simulate communication process MutexWrapper DoWork = MutexPool.Fetch(); Thread testThread = new Thread(new System.Threading.ThreadStart(SimulateCommunicationRandom)); threadList.Add(testThread); testThread.Priority = ThreadPriority.Lowest;//since ui should be normal this is lower priority. DoWork.mutex.WaitOne();//use mutex to lock thread Alert.AlertQueue.Add(new Alert(Addressee, Message));//add the alert to the queue, must be locked to be TS testThread.Start();//start the thread System.Diagnostics.Debug.Write("Running from SentAlert: "+ Thread.CurrentThread.ManagedThreadId +'\n');//see what thread is being used DoWork.mutex.ReleaseMutex();//end lock MutexPool.Return(DoWork);//return the mutex and thread to the pool return true;//success } catch(Exception e)//if there is a problem { //throw e;//I want to see what it is for testing will comment out return false; } //returns message as per HW0 with 4 version numbers and then the message that was passed in //return String.Concat(currentAssemblyName.Version.ToString(), " Received: ", Message);//removed for HW4 }
//returns message as per HW0. Addressee is currently not used for anything public string SendAlert(string Addressee, string Message) { if (Addressee.Length>=1 && Addressee.Substring(0, 1) == "A") { throw new SecureCommunicationException("Addressee Starts with invalid charicter: A"); } if (Addressee.Length>=1 && Addressee.Substring(0,1)== "B") { int zero = 0; int bad = 1 / zero; }//divide by 0 if (Addressee.Length >= 1 && Addressee.Substring(0, 1) == "C") { try{ int zero = 0; int bad = 1 / zero;//divide by 0 } catch (System.DivideByZeroException){ DivideByZeroException e = new DivideByZeroException(); throw new SecureCommunicationException(Addressee, "Tried to divide by Zero", e); } } Assembly currentAssembly = typeof(Communicator).Assembly; //saves current assembly type AssemblyName currentAssemblyName = currentAssembly.GetName(); //gets the current assembly name //returns message as per HW0 with 4 version numbers and then the message that was passed in return String.Concat(currentAssemblyName.Version.ToString(), " Received: ", Message); }
public void read_aggregate_exception() { var ex1 = new DivideByZeroException("Only Chuck Norris can do that"); var ex2 = new RankException("You're last!"); var ex3 = new InvalidTimeZoneException("You are in the wrong place!"); var ex = new AggregateException(ex1, ex2, ex3); var record = new JobExecutionRecord(); record.ReadException(ex); record.ExceptionText.ShouldNotBe(ex.ToString()); record.ExceptionText.ShouldContain(ex1.ToString()); record.ExceptionText.ShouldContain(ex2.ToString()); record.ExceptionText.ShouldContain(ex3.ToString()); record.ExceptionText.ShouldContain(JobExecutionRecord.ExceptionSeparator); }
public async Task Executing_the_policy_action_and_failing_with_a_defined_exception_type_should_return_failure_result_indicating_that_exception_type_is_one_handled_by_this_policy() { var definedException = new DivideByZeroException(); var result = await Policy .Handle<DivideByZeroException>() .RetryAsync((_, __) => { }) .ExecuteAndCaptureAsync(() => { throw definedException; }); result.ShouldBeEquivalentTo(new { Outcome = OutcomeType.Failure, FinalException = definedException, ExceptionType = ExceptionType.HandledByThisPolicy }); }
public void execute_sad_path() { var context = SpecContext.ForTesting(); var ex = new DivideByZeroException(); var section = new Section("Math") {id = "5"}; var action = new SilentAction("Fixture", Stage.teardown, x => { throw ex; }, section); action.Execute(context); var result = context.Results.Single().ShouldBeOfType<StepResult>(); result.id.ShouldBe(section.id); result.position.ShouldBe(Stage.teardown.ToString()); result.status.ShouldBe(ResultStatus.error); result.error.ShouldContain("DivideByZeroException"); }
public void CallSiteCorrectWhenMixinThrowsAnError() { var divideByZeroException = new DivideByZeroException(); var input = @" .mixin(@a: 5px) { width: 10px / @a; } .error { .mixin(0px); }"; AssertError( divideByZeroException.Message, " width: 10px / @a;", 2, 14, " .mixin(0px);", 5, input); }
public void log_execute_failure_1() { var ex = new DivideByZeroException(); var logger = new RecordingLogger(); using (var connection = new ManagedConnection(new ConnectionSource()) {Logger = logger}) { Exception<DivideByZeroException>.ShouldBeThrownBy(() => { connection.Execute(c => { c.CommandText = "do something"; throw ex; }); }); logger.LastCommand.CommandText.ShouldBe("do something"); logger.LastException.ShouldBe(ex); } }
public async Task AsyncEnumerable_Materialize_handles_OnError_correctly() { var ex = new DivideByZeroException(); var notifications = await AsyncEnumerable.Range(0, 100) .Take(10) .Concat(AsyncEnumerable.Throw<int>(ex)) .Materialize() .ToArray(); Assert.Equal(11, notifications.Length); for (var i = 0; i < notifications.Length - 1; i++) { Assert.Equal(NotificationKind.OnNext, notifications[i].Kind); Assert.Equal(i, notifications[i].Value); } var lastNotificaton = notifications.Last(); Assert.Equal(NotificationKind.OnError, lastNotificaton.Kind); Assert.Equal(ex, lastNotificaton.Exception); }
public void CanAppendMessageWithException() { //-- Arrange var logger = CreateTestLogger(); var exception = new DivideByZeroException(); //-- Act logger.ThisIsMyErrorMessageWithExceptionParameter(num: 123, str: "ABC", e: exception); //-- Assert var log = _logAppender.TakeLog(); Assert.That(log.Length, Is.EqualTo(1)); Assert.That(log[0].Level, Is.EqualTo(LogLevel.Error)); Assert.That(log[0].SingleLineText, Is.EqualTo("This is my error message with exception parameter: num=123, str=ABC")); Assert.That(log[0].FullDetailsText.Contains(exception.ToString())); Assert.That(log[0].Exception, Is.SameAs(exception)); }
public void log_exception_once() { var subject1 = MockRepository.GenerateMock<ISubject>(); var subject2 = MockRepository.GenerateMock<ISubject>(); var log = new StubbedChainExecutionLog(); log.StartSubject(subject1); log.StartSubject(subject2); var ex = new DivideByZeroException(); log.LogException(ex); log.FinishSubject(); log.LogException(ex); log.FinishSubject(); log.LogException(ex); log.Steps.Select(x => x.Log).OfType<ExceptionReport>() .Single().ExceptionText.ShouldBe(ex.ToString()); }
public void Catch4() { var ex = new DivideByZeroException(); var err = false; var xs = new[] { 1, 2, 3 }.ToAsyncEnumerable().Concat(AsyncEnumerable.Throw<int>(ex)); var ys = new[] { 4, 5, 6 }.ToAsyncEnumerable(); var res = xs.Catch<int, InvalidOperationException>(ex_ => { err = true; return ys; }); var e = res.GetEnumerator(); HasNext(e, 1); HasNext(e, 2); HasNext(e, 3); AssertThrows<Exception>(() => e.MoveNext().Wait(), ex_ => ((AggregateException)ex_).Flatten().InnerExceptions.Single() == ex); Assert.False(err); }
/// <summary> /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException. /// and in winrt and marshal APIs as Exception. /// </summary> /// <param name="errorCode"></param> /// <param name="message"></param> /// <param name="createCOMException"></param> /// <returns></returns> internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo) { if (errorCode >= 0) { return null; } Exception exception = null; bool shouldDisplayHR = false; switch (errorCode) { case __HResults.COR_E_NOTFINITENUMBER: // NotFiniteNumberException case __HResults.COR_E_ARITHMETIC: exception = new ArithmeticException(); break; case __HResults.COR_E_ARGUMENT: case unchecked((int)0x800A01C1): case unchecked((int)0x800A01C2): case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT: exception = new ArgumentException(); if (errorCode != __HResults.COR_E_ARGUMENT) shouldDisplayHR = true; break; case __HResults.E_BOUNDS: case __HResults.COR_E_ARGUMENTOUTOFRANGE: case __HResults.ERROR_NO_UNICODE_TRANSLATION: exception = new ArgumentOutOfRangeException(); if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE) shouldDisplayHR = true; break; case __HResults.COR_E_ARRAYTYPEMISMATCH: exception = new ArrayTypeMismatchException(); break; case __HResults.COR_E_BADIMAGEFORMAT: case __HResults.CLDB_E_FILE_OLDVER: case __HResults.CLDB_E_INDEX_NOTFOUND: case __HResults.CLDB_E_FILE_CORRUPT: case __HResults.COR_E_NEWER_RUNTIME: case __HResults.COR_E_ASSEMBLYEXPECTED: case __HResults.ERROR_BAD_EXE_FORMAT: case __HResults.ERROR_EXE_MARKED_INVALID: case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT: case __HResults.ERROR_NOACCESS: case __HResults.ERROR_INVALID_ORDINAL: case __HResults.ERROR_INVALID_DLL: case __HResults.ERROR_FILE_CORRUPT: case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY: case __HResults.META_E_BAD_SIGNATURE: exception = new BadImageFormatException(); // Always show HR for BadImageFormatException shouldDisplayHR = true; break; case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT: exception = new FormatException(); break; // CustomAttributeFormatException case __HResults.COR_E_DATAMISALIGNED: exception = InteropExtensions.CreateDataMisalignedException(message); // TODO: Do we need to add msg here? break; case __HResults.COR_E_DIVIDEBYZERO: case __HResults.CTL_E_DIVISIONBYZERO: exception = new DivideByZeroException(); if (errorCode != __HResults.COR_E_DIVIDEBYZERO) shouldDisplayHR = true; break; case __HResults.COR_E_DLLNOTFOUND: #if ENABLE_WINRT exception = new DllNotFoundException(); #endif break; case __HResults.COR_E_DUPLICATEWAITOBJECT: exception = new ArgumentException(); break; // DuplicateWaitObjectException case __HResults.COR_E_ENDOFSTREAM: case unchecked((int)0x800A003E): exception = new System.IO.EndOfStreamException(); if (errorCode != __HResults.COR_E_ENDOFSTREAM) shouldDisplayHR = true; break; case __HResults.COR_E_TYPEACCESS: // TypeAccessException case __HResults.COR_E_ENTRYPOINTNOTFOUND: exception = new TypeLoadException(); break; // EntryPointNotFoundException case __HResults.COR_E_EXCEPTION: exception = new Exception(); break; case __HResults.COR_E_DIRECTORYNOTFOUND: case __HResults.STG_E_PATHNOTFOUND: case __HResults.CTL_E_PATHNOTFOUND: exception = new System.IO.DirectoryNotFoundException(); if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND) shouldDisplayHR = true; break; case __HResults.COR_E_FILELOAD: case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION: case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED: case __HResults.FUSION_E_LOADFROM_BLOCKED: case __HResults.FUSION_E_CACHEFILE_FAILED: case __HResults.FUSION_E_ASM_MODULE_MISSING: case __HResults.FUSION_E_INVALID_NAME: case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED: case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH: case __HResults.COR_E_MODULE_HASH_CHECK_FAILED: case __HResults.FUSION_E_REF_DEF_MISMATCH: case __HResults.SECURITY_E_INCOMPATIBLE_SHARE: case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE: case __HResults.SECURITY_E_UNVERIFIABLE: case __HResults.COR_E_FIXUPSINEXE: case __HResults.ERROR_TOO_MANY_OPEN_FILES: case __HResults.ERROR_SHARING_VIOLATION: case __HResults.ERROR_LOCK_VIOLATION: case __HResults.ERROR_OPEN_FAILED: case __HResults.ERROR_DISK_CORRUPT: case __HResults.ERROR_UNRECOGNIZED_VOLUME: case __HResults.ERROR_DLL_INIT_FAILED: case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED: case __HResults.CORSEC_E_MISSING_STRONGNAME: case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS: case __HResults.ERROR_FILE_INVALID: exception = new System.IO.FileLoadException(); shouldDisplayHR = true; break; case __HResults.COR_E_PATHTOOLONG: exception = new System.IO.PathTooLongException(); break; case __HResults.COR_E_IO: case __HResults.CTL_E_DEVICEIOERROR: case unchecked((int)0x800A793C): case unchecked((int)0x800A793D): exception = new System.IO.IOException(); if (errorCode != __HResults.COR_E_IO) shouldDisplayHR = true; break; case __HResults.ERROR_FILE_NOT_FOUND: case __HResults.ERROR_MOD_NOT_FOUND: case __HResults.ERROR_INVALID_NAME: case __HResults.CTL_E_FILENOTFOUND: case __HResults.ERROR_BAD_NET_NAME: case __HResults.ERROR_BAD_NETPATH: case __HResults.ERROR_NOT_READY: case __HResults.ERROR_WRONG_TARGET_NAME: case __HResults.INET_E_UNKNOWN_PROTOCOL: case __HResults.INET_E_CONNECTION_TIMEOUT: case __HResults.INET_E_CANNOT_CONNECT: case __HResults.INET_E_RESOURCE_NOT_FOUND: case __HResults.INET_E_OBJECT_NOT_FOUND: case __HResults.INET_E_DOWNLOAD_FAILURE: case __HResults.INET_E_DATA_NOT_AVAILABLE: case __HResults.ERROR_DLL_NOT_FOUND: case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW: case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH: case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND: exception = new System.IO.FileNotFoundException(); shouldDisplayHR = true; break; case __HResults.COR_E_FORMAT: exception = new FormatException(); break; case __HResults.COR_E_INDEXOUTOFRANGE: case unchecked((int)0x800a0009): exception = new IndexOutOfRangeException(); if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE) shouldDisplayHR = true; break; case __HResults.COR_E_INVALIDCAST: exception = new InvalidCastException(); break; case __HResults.COR_E_INVALIDCOMOBJECT: exception = new InvalidComObjectException(); break; case __HResults.COR_E_INVALIDOLEVARIANTTYPE: exception = new InvalidOleVariantTypeException(); break; case __HResults.COR_E_INVALIDOPERATION: case __HResults.E_ILLEGAL_STATE_CHANGE: case __HResults.E_ILLEGAL_METHOD_CALL: case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT: case __HResults.APPMODEL_ERROR_NO_PACKAGE: exception = new InvalidOperationException(); if (errorCode != __HResults.COR_E_INVALIDOPERATION) shouldDisplayHR = true; break; case __HResults.COR_E_MARSHALDIRECTIVE: exception = new MarshalDirectiveException(); break; case __HResults.COR_E_METHODACCESS: // MethodAccessException case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException case __HResults.COR_E_FIELDACCESS: case __HResults.COR_E_MEMBERACCESS: exception = new MemberAccessException(); if (errorCode != __HResults.COR_E_METHODACCESS) shouldDisplayHR = true; break; case __HResults.COR_E_MISSINGFIELD: // MissingFieldException case __HResults.COR_E_MISSINGMETHOD: // MissingMethodException case __HResults.COR_E_MISSINGMEMBER: case unchecked((int)0x800A01CD): exception = new MissingMemberException(); break; case __HResults.COR_E_MISSINGMANIFESTRESOURCE: exception = new System.Resources.MissingManifestResourceException(); break; case __HResults.COR_E_NOTSUPPORTED: case unchecked((int)0x800A01B6): case unchecked((int)0x800A01BD): case unchecked((int)0x800A01CA): case unchecked((int)0x800A01CB): exception = new NotSupportedException(); if (errorCode != __HResults.COR_E_NOTSUPPORTED) shouldDisplayHR = true; break; case __HResults.COR_E_NULLREFERENCE: exception = new NullReferenceException(); break; case __HResults.COR_E_OBJECTDISPOSED: case __HResults.RO_E_CLOSED: // No default constructor exception = new ObjectDisposedException(String.Empty); break; case __HResults.COR_E_OPERATIONCANCELED: #if ENABLE_WINRT exception = new OperationCanceledException(); #endif break; case __HResults.COR_E_OVERFLOW: case __HResults.CTL_E_OVERFLOW: exception = new OverflowException(); break; case __HResults.COR_E_PLATFORMNOTSUPPORTED: exception = new PlatformNotSupportedException(message); break; case __HResults.COR_E_RANK: exception = new RankException(); break; case __HResults.COR_E_REFLECTIONTYPELOAD: #if ENABLE_WINRT exception = new System.Reflection.ReflectionTypeLoadException(null, null); #endif break; case __HResults.COR_E_SECURITY: case __HResults.CORSEC_E_INVALID_STRONGNAME: case __HResults.CTL_E_PERMISSIONDENIED: case unchecked((int)0x800A01A3): case __HResults.CORSEC_E_INVALID_PUBLICKEY: case __HResults.CORSEC_E_SIGNATURE_MISMATCH: exception = new System.Security.SecurityException(); break; case __HResults.COR_E_SAFEARRAYRANKMISMATCH: exception = new SafeArrayRankMismatchException(); break; case __HResults.COR_E_SAFEARRAYTYPEMISMATCH: exception = new SafeArrayTypeMismatchException(); break; case __HResults.COR_E_SERIALIZATION: exception = new System.Runtime.Serialization.SerializationException(message); break; case __HResults.COR_E_SYNCHRONIZATIONLOCK: exception = new System.Threading.SynchronizationLockException(); break; case __HResults.COR_E_TARGETINVOCATION: exception = new System.Reflection.TargetInvocationException(null); break; case __HResults.COR_E_TARGETPARAMCOUNT: exception = new System.Reflection.TargetParameterCountException(); break; case __HResults.COR_E_TYPEINITIALIZATION: exception = InteropExtensions.CreateTypeInitializationException(message); break; case __HResults.COR_E_TYPELOAD: case __HResults.RO_E_METADATA_NAME_NOT_FOUND: case __HResults.CLR_E_BIND_TYPE_NOT_FOUND: exception = new TypeLoadException(); if (errorCode != __HResults.COR_E_TYPELOAD) shouldDisplayHR = true; break; case __HResults.COR_E_UNAUTHORIZEDACCESS: case __HResults.CTL_E_PATHFILEACCESSERROR: case unchecked((int)0x800A014F): exception = new UnauthorizedAccessException(); shouldDisplayHR = true; break; case __HResults.COR_E_VERIFICATION: exception = new System.Security.VerificationException(); break; case __HResults.E_NOTIMPL: exception = new NotImplementedException(); break; case __HResults.E_OUTOFMEMORY: case __HResults.CTL_E_OUTOFMEMORY: case unchecked((int)0x800A7919): exception = new OutOfMemoryException(); if (errorCode != __HResults.E_OUTOFMEMORY) shouldDisplayHR = true; break; #if ENABLE_WINRT case __HResults.E_XAMLPARSEFAILED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTAVAILABLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTENABLED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_LAYOUTCYCLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; #endif // ENABLE_WINRT case __HResults.COR_E_AMBIGUOUSMATCH: // AmbiguousMatchException case __HResults.COR_E_APPLICATION: // ApplicationException case __HResults.COR_E_APPDOMAINUNLOADED: // AppDomainUnloadedException case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN: // CannotUnloadAppDomainException case __HResults.COR_E_CODECONTRACTFAILED: // ContractException case __HResults.COR_E_CONTEXTMARSHAL: // ContextMarshalException case __HResults.CORSEC_E_CRYPTO: // CryptographicException case __HResults.CORSEC_E_CRYPTO_UNEX_OPER: // CryptographicUnexpectedOperationException case __HResults.COR_E_EXECUTIONENGINE: // ExecutionEngineException case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException case __HResults.COR_E_INVALIDFILTERCRITERIA: // InvalidFilterCriteriaException case __HResults.COR_E_INVALIDPROGRAM: // InvalidProgramException case __HResults.COR_E_MULTICASTNOTSUPPORTED: // MulticastNotSupportedException case __HResults.COR_E_REMOTING: // RemotingException case __HResults.COR_E_RUNTIMEWRAPPED: // RuntimeWrappedException case __HResults.COR_E_SERVER: // ServerException case __HResults.COR_E_STACKOVERFLOW: // StackOverflowException case __HResults.CTL_E_OUTOFSTACKSPACE: // StackOverflowException case __HResults.COR_E_SYSTEM: // SystemException case __HResults.COR_E_TARGET: // TargetException case __HResults.COR_E_THREADABORTED: // TargetException case __HResults.COR_E_THREADINTERRUPTED: // ThreadInterruptedException case __HResults.COR_E_THREADSTATE: // ThreadStateException case __HResults.COR_E_THREADSTART: // ThreadStartException case __HResults.COR_E_TYPEUNLOADED: // TypeUnloadedException case __HResults.CORSEC_E_POLICY_EXCEPTION: // PolicyException case __HResults.CORSEC_E_NO_EXEC_PERM: // PolicyException case __HResults.CORSEC_E_MIN_GRANT_FAIL: // PolicyException case __HResults.CORSEC_E_XMLSYNTAX: // XmlSyntaxException case __HResults.ISS_E_ALLOC_TOO_LARGE: // IsolatedStorageException case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL: // IsolatedStorageException case __HResults.ISS_E_CALLER: // IsolatedStorageException case __HResults.ISS_E_CORRUPTED_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_CREATE_DIR: // IsolatedStorageException case __HResults.ISS_E_CREATE_MUTEX: // IsolatedStorageException case __HResults.ISS_E_DEPRECATE: // IsolatedStorageException case __HResults.ISS_E_FILE_NOT_MAPPED: // IsolatedStorageException case __HResults.ISS_E_FILE_WRITE: // IsolatedStorageException case __HResults.ISS_E_GET_FILE_SIZE: // IsolatedStorageException case __HResults.ISS_E_ISOSTORE: // IsolatedStorageException case __HResults.ISS_E_LOCK_FAILED: // IsolatedStorageException case __HResults.ISS_E_MACHINE: // IsolatedStorageException case __HResults.ISS_E_MACHINE_DACL: // IsolatedStorageException case __HResults.ISS_E_MAP_VIEW_OF_FILE: // IsolatedStorageException case __HResults.ISS_E_OPEN_FILE_MAPPING: // IsolatedStorageException case __HResults.ISS_E_OPEN_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_PATH_LENGTH: // IsolatedStorageException case __HResults.ISS_E_SET_FILE_POINTER: // IsolatedStorageException case __HResults.ISS_E_STORE_NOT_OPEN: // IsolatedStorageException case __HResults.ISS_E_STORE_VERSION: // IsolatedStorageException case __HResults.ISS_E_TABLE_ROW_NOT_FOUND: // IsolatedStorageException case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA: // IsolatedStorageException case __HResults.E_FAIL: default: break; } if (exception == null) { if (createCOMException) { exception = new COMException(); if (errorCode != __HResults.E_FAIL) shouldDisplayHR = true; } else { exception = new Exception(); if (errorCode != __HResults.COR_E_EXCEPTION) shouldDisplayHR = true; } } bool shouldConstructMessage = false; if (hasErrorInfo) { // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if // the message is not available and do not use the shouldDisplayHR setting if (message == null) shouldConstructMessage = true; } else { // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above shouldConstructMessage = shouldDisplayHR; } if (shouldConstructMessage) { // // Append the HR into error message, just in case the app wants to look at the HR in // message to determine behavior. We didn't expose HResult property until v4.5 and // GetHRFromException has side effects so probably Message was their only choice. // This behavior is probably not exactly the same as in desktop but it is fine to append // more message at the end. In any case, having the HR in the error message are helpful // to developers. // This makes sure: // 1. We always have a HR 0xNNNNNNNN in the message // 2. Put in a nice "Exception thrown from HRESULT" message if we can // 3. Wrap it in () if there is an existing message // // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString()); message = ExternalInterop.GetMessage(errorCode); // Always make sure we have at least the HRESULT part in retail build or when the message // is empty. if (message == null) message = hrMessage; else message = message + " (" + hrMessage + ")"; } if (message != null) { // Set message explicitly rather than calling constructor because certain ctors would append a // prefix to the message and that is not what we want InteropExtensions.SetExceptionMessage(exception, message); } InteropExtensions.SetExceptionErrorCode(exception, errorCode); return exception; }