Pular para o conteúdo principal
ProdutosFerramentas de desktopTASTECADVisualização de desenhosTASTEFILESGerenciamento de arquivosTASTEFTPTransferência de arquivosTASTESSHEspaço de trabalho remotoTASTEZIPCompactação e extraçãoFerramentas para desenvolvedoresTASTECODEAmbiente de desenvolvimento integrado para RustTASTESTUDIOAmbiente integrado de desenvolvimento e testesTASTEETLIntegração de dados (ETL)ServidoresTASTEREMOTEServidor de área de trabalho remotaTASTEGEOServidor geoespacialTASTEMAILEspaço de trabalho de e-mailComeçarDownloadsDocumentaçãoComprarTodos os produtos
Marketplace
Notícias
TecnologiaNotíciasNotícias de desenvolvimento de hojeDocumentaçãoLinguagens de programaçãoRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps e desktopTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos essenciaisAlgoritmos avançadosAlgoritmos práticos
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrineGuia da comunidade
ColaboreTransferência técnicaConstrução de siteConstrução de app de desktopPipeline de lançamento e pagamentoParceiro de vendasContato
ServiçosÁrea de trabalho remotaPacotes de instalação sob medida
TASTEDEV
Produtos

Ferramentas de desktop

TASTECADDesenhos complexos, abertos com levezaTASTEFILESSó os arquivos de que você precisa, o mais rápido possívelTASTEFTPO caminho mais organizado para seus arquivosTASTESSHEntre você e o servidor, uma conexão mais sólidaTASTEZIPCompacte mais rápido, extraia com mais segurança

Ferramentas para desenvolvedores

TASTECODEEdite, compile, depure e teste apps Rust em uma única janelaTASTESTUDIODa edição aos testes remotos e às correções com IA aprovadasTASTEETLMova dados de olho nos valores

Servidores

TASTEREMOTEUma área de trabalho remota rodando no seu próprio servidorTASTEGEOUm servidor geoespacial compatível com o GeoServer, reconstruído em RustTASTEMAILRetome o controle do seu e-mail

Começar

DownloadsVersões mais recentes de cada produtoDocsComo usar cada produtoComprarAssinaturas e licenças perpétuasTodos os produtosTodos os produtos de relance
Todos os produtos
MarketplaceNotícias
Tecnologia

Notícias

Notícias de desenvolvimento de hojeAnúncios oficiais de linguagens, frameworks, GitHub e IADocumentaçãoGuias de linguagens, frameworks e algoritmos

Linguagens de programação

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps e desktopTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálise de complexidade · Ordenação · Busca · Estruturas de dados básicas · Árvores e heapsAlgoritmos essenciaisBusca em grafos · Caminho mínimo e árvore geradora mínima · Programação dinâmica · Algoritmos gulosos · Divisão e conquista · BacktrackingAlgoritmos avançadosAlgoritmos de strings · Matemática e teoria dos números · Manipulação de bits · Árvores de segmentos · Union-FindAlgoritmos práticosEstratégia para entrevistas de código · Cache LRU · Limitação de taxa · Hashing consistente
Toda a documentação de desenvolvimento
Comunidade
ProjetosDescubra criadores e trabalhosRegistros de desenvolvimentoDecisões e aprendizadosPromptsInstruções reutilizáveisProblemas de ferramentas de IAProblemas e contornos de Claude, Codex, GeminiVitrineResultados concluídosGuia da comunidadeComo construímos em aberto
Colabore
Transferência técnicaApps nativos em Rust e eguiConstrução de site10 idiomas, contas, documentação e downloadsConstrução de app de desktopRust e egui, sem WebViewPipeline de lançamento e pagamentoAssinatura, MSI, deb, rpm, AppImage, hashesParceiro de vendasRecomende e ganhe 30%ContatoDesenvolvimento, parcerias e investimento
Serviços
Área de trabalho remotaAcesse seu computador pelo navegadorPacotes de instalação sob medidaSó o necessário, configurações pré-carregadas
Comprar
PT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Entrar
Entrar
TASTEDEV

De pequenas ferramentas a um desenvolvimento melhor.

support@tastedev.netApoiar TASTEDEV
ProdutosLinha de produtosComprarDocsDownloadsMarketplaceSuporte
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrine
PolíticasPolítica de privacidadeTermos de usoTermos de assinaturaReembolsoDiretrizes da comunidade
ContaEntrarCriar conta
Visitantes
Hoje
012345678901234567890123456789012345678901234567890123456789
Ontem
012345678901234567890123456789012345678901234567890123456789
Visualizações totais
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro comercial
853-44-00368
Endereço
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsável pela privacidade
CHOI YOUNG GU

© 2026 TASTEDEVAs informações dos produtos se baseiam em fontes de desenvolvimento verificadas.Lançado · em melhoria

Documentação de C#
C#
Getting Started with CSyntax BasicsTypes and DataProjects and PackagesErrors and TestingKey Concepts: LINQ, Delegates, and Async
Discussões

Guia de C# · 5/6

Errors and Testing

Por enquanto, este capítulo está disponível apenas em 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.

Dúvidas sobre este capítulo?
Capítulo anteriorProjects and PackagesPróximo capítuloKey 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 comentários

Principais comentáriosMais recentes primeiro

Fazer login · Faça login para deixar um comentário.