New to Telerik JustMockStart a free 30-day trial

Throws

Updated on Mar 25, 2026

Use Throws to make a mocked method throw an exception when called. This is the primary way to test that your code correctly handles exceptions thrown by its dependencies.

Here is the system under test for these examples:

C#
public interface IFoo
{
    string Execute(string myStr);
}

Throw Exception on Method Call

Change a method behavior to throw an exception once it is called.

C#
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowExceptionOnMethodCall()
{
    // Arrange
    var foo = Mock.Create<IFoo>();

    Mock.Arrange(() => foo.Execute(string.Empty)).Throws<ArgumentException>();

    // Act
    foo.Execute(string.Empty);
}

The assert step is done via the ExpectedException attribute, where we explicitly specify that an exception of type ArgumentException must be thrown during the execution of the test.

Throw Exception with Arguments on Method Call

Change a method behavior to throw an exception once it is called and pass arguments to the exception.

C#
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowExceptionWithArgumentsOnMethodCall()
{
  // Arrange
  var foo = Mock.Create<IFoo>();

  Mock.Arrange(() => foo.Execute(string.Empty)).Throws<ArgumentException>("Argument shouldn't be empty.");

  // Act
  foo.Execute(string.Empty);
}

The assert step is done via the ExpectedException attribute, where we explicitly specify that an exception of type ArgumentException must be thrown during the execution of the test. Calling foo.Execute with empty string will result in throwing an exception and passing "Argument shouldn't be empty." to it.

See Also