Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguro

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
012345678901234567890123456789012345678901234567890123456789
Ayer
012345678901234567890123456789012345678901234567890123456789
Vistas totales
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de C#
C#
Getting Started with CSyntax BasicsTypes and DataProjects and PackagesErrors and TestingKey Concepts: LINQ, Delegates, and Async
Debates

Guía de C# · 5/6

Errors and Testing

Por ahora, este capítulo solo está disponible en inglés.

C# reports errors with exceptions. When one is thrown, execution unwinds up the call stack until a matching catch block handles it. This chapter covers handling exceptions, cleaning up with using, custom exception types, and unit testing with dotnet test.

try, catch, and finally

The first catch whose type matches wins, so list specific types before general ones. finally always runs, which makes it the place for cleanup.

try
{
    var text = File.ReadAllText("config.json");
    var port = int.Parse(text.Trim());
    Console.WriteLine($"Port: {port}");
}
catch (FileNotFoundException ex)
{
    Console.WriteLine($"Config file not found: {ex.FileName}");
}
catch (FormatException)
{
    Console.WriteLine("The port number is not a valid integer.");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
    Console.WriteLine($"Could not read the file: {ex.Message}");
}
finally
{
    Console.WriteLine("Finished reading configuration.");
}

The when clause is an exception filter: the handler runs only if the condition holds. To rethrow, use a bare throw; so the original stack trace survives; throw ex; restarts the trace and hides the real origin.

When failure is routine, as with user input, prefer the Try pattern: int.TryParse(input, out var value) just returns false.

Guard Clauses and Custom Exceptions

Fail fast on bad arguments using the built-in throw helpers. For domain errors, such as a broken business rule, derive your own type from Exception so callers can catch exactly that case.

public class InsufficientFundsException : Exception
{
    public InsufficientFundsException(decimal balance, decimal requested)
        : base($"Cannot withdraw {requested:F2} from a balance of {balance:F2}.")
    {
        Balance = balance;
        Requested = requested;
    }

    public decimal Balance { get; }
    public decimal Requested { get; }
}

public class Wallet(decimal balance)
{
    public decimal Balance { get; private set; } = balance;

    public void Withdraw(decimal amount, string reason)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
        ArgumentException.ThrowIfNullOrWhiteSpace(reason);

        if (amount > Balance)
            throw new InsufficientFundsException(Balance, amount);

        Balance -= amount;
    }
}

Exception class names end in Exception by convention. Wallet(decimal balance) is a primary constructor, whose parameter is visible across the class.

using and IDisposable

Files, sockets, and database connections implement ; releases what they hold, and guarantees that call even when an exception is thrown.

¿Tienes preguntas sobre este capítulo?
Capítulo anteriorProjects and PackagesCapítulo siguienteKey Concepts: LINQ, Delegates, and Async
IDisposable
Dispose
using
// using statement: disposed at the end of the block (the file is closed)
using (var writer = new StreamWriter("log.txt", append: true))
{
    writer.WriteLine($"{DateTime.Now:O} started");
}

// using declaration: disposed when the enclosing scope ends
using var reader = new StreamReader("log.txt");
Console.WriteLine(reader.ReadLine());

// your own types work with using once they implement IDisposable
using (new ElapsedTimer())
{
    Thread.Sleep(100);
}

sealed class ElapsedTimer : IDisposable
{
    private readonly System.Diagnostics.Stopwatch _watch = System.Diagnostics.Stopwatch.StartNew();
    public void Dispose() => Console.WriteLine($"Elapsed: {_watch.ElapsedMilliseconds} ms");
}

The compiler turns using into try/finally for you. For asynchronous cleanup (IAsyncDisposable), use await using.

Unit Testing with xUnit

The main .NET test frameworks are xUnit, NUnit, and MSTest. Assuming Wallet lives in a src/Wallet library, add an xUnit project like this:

dotnet new xunit -o tests/Wallet.Tests
dotnet sln add tests/Wallet.Tests
dotnet add tests/Wallet.Tests reference src/Wallet

dotnet test                                         # run every test
dotnet test --filter "FullyQualifiedName~Withdraw"  # run tests whose names match
using Xunit;

public class WalletTests
{
    [Fact]
    public void Withdraw_DecreasesBalance()
    {
        var wallet = new Wallet(100m);

        wallet.Withdraw(30m, "lunch");

        Assert.Equal(70m, wallet.Balance);
    }

    [Fact]
    public void Withdraw_MoreThanBalance_Throws()
    {
        var wallet = new Wallet(10m);

        var ex = Assert.Throws<InsufficientFundsException>(() => wallet.Withdraw(50m, "book"));
        Assert.Equal(50m, ex.Requested);
    }

    [Theory]
    [InlineData(0)]
    [InlineData(-100)]
    public void Withdraw_InvalidAmount_Throws(int amount)
    {
        var wallet = new Wallet(10m);
        Assert.Throws<ArgumentOutOfRangeException>(() => wallet.Withdraw(amount, "bad amount"));
    }
}

A [Fact] takes no inputs; a [Theory] runs once per [InlineData] row. Arrange, Act, Assert keeps each test easy to scan.

If You Prefer MSTest

MSTest, Microsoft's own framework, differs mainly in naming. Start with dotnet new mstest.

using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class WalletTests
{
    [TestMethod]
    public void Withdraw_DecreasesBalance()
    {
        var wallet = new Wallet(100m);
        wallet.Withdraw(30m, "lunch");
        Assert.AreEqual(70m, wallet.Balance);
    }
}
TaskxUnitMSTest
Test method[Fact][TestMethod]
Parameterized test[Theory] + [InlineData][TestMethod] + [DataRow]
Equality checkAssert.EqualAssert.AreEqual
Per-test setupconstructor[TestInitialize]

Summary

  • Use try/catch/finally, catch specific types first, and rethrow with throw;.
  • Use the Try pattern for routine failures and custom exceptions for domain errors.
  • Wrap IDisposable objects in using so cleanup always runs.
  • Create a test project with dotnet new xunit (or mstest) and run it with dotnet test.

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.