Partager via


Procédure : intercepter des exceptions

Dernière modification : mercredi 24 mars 2010

S’applique à : SharePoint Server 2010

Placez les sections de code susceptibles de lever des exceptions dans un bloc try, puis placez le code qui gère les exceptions dans un bloc catch. L'ordre des instructions catch est important. Lorsqu'une exception se produit, elle remonte la pile et chaque bloc catch a la possibilité de la traiter. Le bloc catch qui doit gérer l'exception est déterminé par la mise en correspondance du type de l'exception et du nom de l'exception spécifié dans le bloc catch. Par exemple, le bloc catch suivant intercepte les exceptions SOAP (Simple Object Access Protocol) :

catch (SoapException e)
{
    Console.WriteLine("SOAP Exception Error Code: {0}", 
        e.SubCode.Code.Name);
    Console.WriteLine("SOAP Exception Message is: {0}", 
        e.Message);
}
Catch e As SoapException
    Console.WriteLine("SOAP Exception Error Code: {0}", e.SubCode.Code.Name)
    Console.WriteLine("SOAP Exception Message is: {0}", e.Message)
End Try

Si aucun bloc catch spécifique n'existe, l'exception est interceptée par un bloc catch général, le cas échéant. Vous pouvez par exemple intercepter des exceptions générales en ajoutant le code suivant :

catch (Exception e)
{
    Console.WriteLine("Exception Message: {0}", e.Message);
}
Catch e As Exception
    Console.WriteLine("Exception Message: {0}", e.Message)
End Try

Placez les blocs catch ciblés pour des exceptions spécifiques avant un bloc catch d'exception général.

L’environnement CLR (Common Language Runtime) intercepte des exceptions qui ne sont pas interceptées par un bloc catch. Selon la configuration de l’environnement d’exécution, une boîte de dialogue de débogage s’affiche ou le programme cesse de s’exécuter, et une boîte de dialogue contenant des informations sur l’exception s’affiche. Pour plus d’informations sur le débogage, voir Débogage et profilage d’applications (éventuellement en anglais) (https://msdn.microsoft.com/fr-fr/library/7fe0dd2y(vs.71).aspx).

Pour plus d’informations sur la gestion des exceptions, voir Meilleures pratiques pour la gestion des exceptions (éventuellement en anglais) (https://msdn.microsoft.com/fr-fr/library/seyhszts(vs.71).aspx).

Exemple

using System;
using System.Text;
using System.Web.Services.Protocols;
using ExcelWebService.myserver02;
namespace ExcelWebService
{
    class WebService
    {
        [STAThread]
        static void Main(string[] args)
        {
            // Instantiate the Web service and make a status array object
            ExcelService xlservice = new ExcelService();
            Status[] outStatus;
            RangeCoordinates rangeCoordinates = new RangeCoordinates();
            string sheetName = "Sheet1";

            // Set the path to the workbook to open.
            // TODO: Change the path to the workbook
            // to point to a workbook you have access to.
            // The workbook must be in a trusted location.
            // If workbookPath is a UNC path, the application 
            // must be on the same computer as the server.
            // string targetWorkbookPath = 
            // @"\\MyServer\myxlfiles\Formulas.xlsx";
            string targetWorkbookPath = 
            "http://myserver02/DocLib/Shared%20Documents/Basic1.xlsx";
            // Set credentials for requests
            xlservice.Credentials = 
               System.Net.CredentialCache.DefaultCredentials;

            try
            {
                // Call the OpenWorkbook method and point to the 
                // trusted location of the workbook to open.
                string sessionId = xlservice.OpenWorkbook(targetWorkbookPath, "en-US", "en-US", out outStatus);
                Console.WriteLine("sessionID : {0}", sessionId);
                // Prepare object to define range coordinates, 
                // and call the GetRange method.
                rangeCoordinates.Column = 0;
                rangeCoordinates.Row = 0;
                rangeCoordinates.Height = 18;
                rangeCoordinates.Width = 10;

                object[] rangeResult1 = xlservice.GetRange(sessionId, sheetName, rangeCoordinates, false, out outStatus);
                Console.WriteLine("Total rows in range: " + rangeResult1.Length);

                Console.WriteLine("Sum in last column is: " + ((object[])rangeResult1[2])[3]);

               // Close the workbook. This also closes the session.
                xlservice.CloseWorkbook(sessionId);
            }
            catch (SoapException e)
            {
                Console.WriteLine("SOAP Exception Error Code: {0}", 
                    e.SubCode.Code.Name);
                Console.WriteLine("SOAP Exception Message is: {0}", 
                    e.Message);
            }

            catch (Exception e)
            {
                Console.WriteLine("Exception Message: {0}", e.Message);
            }
            Console.ReadLine();
        }
    }
}
Imports System
Imports System.Text
Imports System.Web.Services.Protocols
Imports ExcelWebService.myserver02
Namespace ExcelWebService
    Friend Class WebService
        <STAThread> _
        Shared Sub Main(ByVal args() As String)
            ' Instantiate the Web service and make a status array object
            Dim xlservice As New ExcelService()
            Dim outStatus() As Status
            Dim rangeCoordinates As New RangeCoordinates()
            Dim sheetName As String = "Sheet1"

            ' Set the path to the workbook to open.
            ' TODO: Change the path to the workbook
            ' to point to a workbook you have access to.
            ' The workbook must be in a trusted location.
            ' If workbookPath is a UNC path, the application 
            ' must be on the same computer as the server.
            ' string targetWorkbookPath = 
            ' @"\\MyServer\myxlfiles\Formulas.xlsx";
            Dim targetWorkbookPath As String = "http://myserver02/DocLib/Shared%20Documents/Basic1.xlsx"
            ' Set credentials for requests
            xlservice.Credentials = System.Net.CredentialCache.DefaultCredentials

            Try
                ' Call the OpenWorkbook method and point to the 
                ' trusted location of the workbook to open.
                Dim sessionId As String = xlservice.OpenWorkbook(targetWorkbookPath, "en-US", "en-US", outStatus)
                Console.WriteLine("sessionID : {0}", sessionId)
                ' Prepare object to define range coordinates, 
                ' and call the GetRange method.
                rangeCoordinates.Column = 0
                rangeCoordinates.Row = 0
                rangeCoordinates.Height = 18
                rangeCoordinates.Width = 10

                Dim rangeResult1() As Object = xlservice.GetRange(sessionId, sheetName, rangeCoordinates, False, outStatus)
                Console.WriteLine("Total rows in range: " & rangeResult1.Length)

                Console.WriteLine("Sum in last column is: " & (CType(rangeResult1(2), Object()))(3))

               ' Close the workbook. This also closes the session.
                xlservice.CloseWorkbook(sessionId)
            Catch e As SoapException
                Console.WriteLine("SOAP Exception Error Code: {0}", e.SubCode.Code.Name)
                Console.WriteLine("SOAP Exception Message is: {0}", e.Message)

            Catch e As Exception
                Console.WriteLine("Exception Message: {0}", e.Message)
            End Try
            Console.ReadLine()
        End Sub
    End Class
End Namespace

Voir aussi

Tâches

Procédure pas à pas : développement d'une application personnalisée à l'aide des services Web Excel

Procédure : Approuver un emplacement

Procédure : Enregistrer sur le serveur à partir du client Excel

Procédure : utiliser la propriété SubCode pour capturer des codes d'erreur

Concepts

Accès à l'API SOAP

Excel Services Alerts

Problèmes connus et conseils Excel Services

Appels SOAP de retour de boucle et liaison directe