在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
处理异常 在 C# 中,正确地使用 catch 子句至关重要。本教程将向您展示如何使用带有多个 catch 子句的 try-catch 块。我们将介绍如何捕获多种异常类型、使用异常过滤器并确保资源得到最终清理。目的是帮助您构建健壮、容错的 C# 应用程序。
通过学习捕获多种类型的异常,您可以针对具体问题定制响应,从而提高程序的可靠性。我们还将介绍如何使用 when
关键字将条件应用于捕获块,从而实现更精确的错误处理。
本指南将为您提供在编码项目中捕获异常并顺利处理常见和复杂错误的方法。我们还将探讨 IronPDF 在处理异常情况时。
C# 中的异常处理是一种用于处理运行时错误、防止程序突然终止以及管理程序执行过程中出现的意外情况的方法。异常处理的核心组件包括 "try"、"catch "和 "finally "块。
try 块包含可能触发异常的代码,而 catch 块负责在出现异常时对异常进行管理。最后 "代码块是可选的,它会在 "try "和 "catch "代码块之后执行代码,无论异常是否抛出。下面是一个简单的结构:
try {
// Code that may throw an exception
}
catch (Exception e) {
// Code to handle the exception
}
finally {
// Code that executes after try and catch, regardless of an exception
}
try {
// Code that may throw an exception
}
catch (Exception e) {
// Code to handle the exception
}
finally {
// Code that executes after try and catch, regardless of an exception
}
Try
' Code that may throw an exception
Catch e As Exception
' Code to handle the exception
Finally
' Code that executes after try and catch, regardless of an exception
End Try
在实际应用中,单个操作可能会抛出各种类型的异常。为了解决这个问题,C# 允许您为单个 "try "代码块定义多个 "catch "代码块。每个捕获块可以指定不同的异常类型来处理所有异常。
捕获多个异常对于详细的错误处理至关重要,因为错误处理的操作取决于发生的特定错误。它使开发人员能够根据特定错误的上下文以适当的方式处理每个异常。
下面举例说明如何实现一个捕获块捕获多种异常类型:
try {
// Code that may throw multiple types of exceptions
int[] numbers = {1, 2, 3};
Console.WriteLine(numbers[5]); // This will throw an IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex) {
Console.WriteLine("An index was out of range: " + ex.Message);
}
catch (DivideByZeroException ex) {
Console.WriteLine("Can't divide by Zero: " + ex.Message);
}
catch (Exception ex) {
Console.WriteLine("Error: " + ex.Message);
}
try {
// Code that may throw multiple types of exceptions
int[] numbers = {1, 2, 3};
Console.WriteLine(numbers[5]); // This will throw an IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex) {
Console.WriteLine("An index was out of range: " + ex.Message);
}
catch (DivideByZeroException ex) {
Console.WriteLine("Can't divide by Zero: " + ex.Message);
}
catch (Exception ex) {
Console.WriteLine("Error: " + ex.Message);
}
Try
' Code that may throw multiple types of exceptions
Dim numbers() As Integer = {1, 2, 3}
Console.WriteLine(numbers(5)) ' This will throw an IndexOutOfRangeException
Catch ex As IndexOutOfRangeException
Console.WriteLine("An index was out of range: " & ex.Message)
Catch ex As DivideByZeroException
Console.WriteLine("Can't divide by Zero: " & ex.Message)
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message)
End Try
在这段代码中,"IndexOutOfRangeException "和 "DivideByZeroException "等特定异常由各自的 "catch "块捕获。其他类型的异常则由通用的 Exception
catch 块捕获。
C# 还支持异常过滤器,允许您在 catch 代码块中指定一个条件。该功能使用 when
关键字,可根据运行时评估的条件,对捕获哪些异常提供更多控制。
以下是使用 when
关键字添加异常过滤器的方法:
try {
// Code that may throw an exception
throw new InvalidOperationException("Invalid operation occurred", new Exception("Inner exception"));
}
catch (Exception ex) when (ex.InnerException != null) {
Console.WriteLine("Exception with inner exception caught: " + ex.Message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught: " + ex.Message);
}
try {
// Code that may throw an exception
throw new InvalidOperationException("Invalid operation occurred", new Exception("Inner exception"));
}
catch (Exception ex) when (ex.InnerException != null) {
Console.WriteLine("Exception with inner exception caught: " + ex.Message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught: " + ex.Message);
}
Try
' Code that may throw an exception
Throw New InvalidOperationException("Invalid operation occurred", New Exception("Inner exception"))
Catch ex As Exception When ex.InnerException IsNot Nothing
Console.WriteLine("Exception with inner exception caught: " & ex.Message)
Catch ex As Exception
Console.WriteLine("Exception caught: " & ex.Message)
End Try
最后 "代码块用于在 "try "和任何 "catch "代码块完成后执行代码。它可用于清理资源,如关闭文件流或数据库连接,而不管异常是否发生。
try {
// Code that might throw an exception
}
catch (Exception e) {
// Handle the exception
}
finally {
// Cleanup code, executed after try/catch
Console.WriteLine("Cleanup code runs here.");
}
try {
// Code that might throw an exception
}
catch (Exception e) {
// Handle the exception
}
finally {
// Cleanup code, executed after try/catch
Console.WriteLine("Cleanup code runs here.");
}
Try
' Code that might throw an exception
Catch e As Exception
' Handle the exception
Finally
' Cleanup code, executed after try/catch
Console.WriteLine("Cleanup code runs here.")
End Try
IronPDF 是一个综合库,专为在.NET 应用程序中工作的 C# 开发人员设计。它可帮助开发人员操作、管理和 直接从 HTML 创建 PDF 文件. 它不需要外部依赖来工作。
您可以在不使用和安装Adobe Acrobat的情况下执行任何PDF操作。IronPDF支持各种PDF功能,例如编辑、合并、拆分和加密PDF文档以及使用数字签名进行安全保护。开发人员可以在多种应用类型中使用IronPDF,包括Web应用、桌面应用和服务。
链接:
IronPDF的主要功能是转换 HTML 转 PDF,它保留了布局和样式。它非常适合从网页内容生成PDF,无论是报告、发票还是文档。HTML文件、URL和HTML字符串都可以转换为PDF文件。
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class
下面是一个使用 IronPDF 从 HTML 创建 PDF 的简单 C# 示例,其中包含对多种异常类型的错误处理。本示例假定您已在项目中安装了 IronPDF。在 NuGet 控制台中运行此命令安装 IronPDF:
Install-Package IronPdf
代码如下:
using IronPdf;
using System;
class Program
{
static void Main(string[] args)
{
License.LicenseKey = "License-Key";
var renderer = new ChromePdfRenderer();
try
{
// Convert HTML to PDF
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
pdf.SaveAs("Exceptions.pdf");
Console.WriteLine("PDF successfully created.");
}
catch (IronPdf.Exceptions.IronPdfProductException ex)
{
// Handle PDF generation errors
Console.WriteLine("Failed to generate PDF: " + ex.Message);
}
catch (System.IO.IOException ex)
{
// Handle IO errors (e.g., disk I/O errors)
Console.WriteLine("IO Exception: " + ex.Message);
}
catch (Exception ex)
{
// Handle other errors
Console.WriteLine("Error" + ex.Message);
}
}
}
using IronPdf;
using System;
class Program
{
static void Main(string[] args)
{
License.LicenseKey = "License-Key";
var renderer = new ChromePdfRenderer();
try
{
// Convert HTML to PDF
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
pdf.SaveAs("Exceptions.pdf");
Console.WriteLine("PDF successfully created.");
}
catch (IronPdf.Exceptions.IronPdfProductException ex)
{
// Handle PDF generation errors
Console.WriteLine("Failed to generate PDF: " + ex.Message);
}
catch (System.IO.IOException ex)
{
// Handle IO errors (e.g., disk I/O errors)
Console.WriteLine("IO Exception: " + ex.Message);
}
catch (Exception ex)
{
// Handle other errors
Console.WriteLine("Error" + ex.Message);
}
}
}
Imports IronPdf
Imports System
Friend Class Program
Shared Sub Main(ByVal args() As String)
License.LicenseKey = "License-Key"
Dim renderer = New ChromePdfRenderer()
Try
' Convert HTML to PDF
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>")
pdf.SaveAs("Exceptions.pdf")
Console.WriteLine("PDF successfully created.")
Catch ex As IronPdf.Exceptions.IronPdfProductException
' Handle PDF generation errors
Console.WriteLine("Failed to generate PDF: " & ex.Message)
Catch ex As System.IO.IOException
' Handle IO errors (e.g., disk I/O errors)
Console.WriteLine("IO Exception: " & ex.Message)
Catch ex As Exception
' Handle other errors
Console.WriteLine("Error" & ex.Message)
End Try
End Sub
End Class
当我们运行这段代码时,命令行中会显示如下信息。
这就是这段代码生成的 PDF 文件:
确保在 IronPDF 已正确配置的环境中进行测试,并根据应用需要修改 HTML 内容。这将帮助您有效管理错误,提高 PDF 生成任务的可靠性。
在 C# 中处理多个异常是一项强大的功能,可为应用程序提供强大的错误处理能力。通过使用多个 "catch "块、异常过滤器和 "finally "块,您可以创建一个弹性和稳定的应用程序,它可以优雅地处理不同的错误,并在各种错误条件下保持其完整性。
对多重异常处理的全面理解和实施可确保您的应用程序做好充分准备,有效应对意外情况。IronPDF 提供 免费试用 从 $749 开始。