Как игнорировать ошибку в visual studio

title description ms.date ms.technology ms.topic author ms.author manager ms.workload

Suppress warnings for projects and NuGet packages

Learn how you can use Visual Studio to declutter a build log by filtering out one or more kinds of compiler warnings.

06/10/2022

vs-ide-compile

how-to

ghogen

ghogen

jmartens

multiple

How to: Suppress compiler warnings

[!INCLUDE Visual Studio]

You can declutter a build log by filtering out one or more kinds of compiler warnings. For example, you might want to review only some of the output that’s generated when you set the build log verbosity to Normal, Detailed, or Diagnostic. For more information about verbosity, see How to: View, save, and configure build log files.

Suppress specific warnings for Visual C# or F#

Use the Build properties to suppress specific warnings for C# and F# projects.

:::moniker range=»>=vs-2022″

  1. In Solution Explorer, choose the project in which you want to suppress warnings.

  2. Right-click on the project node, and choose Properties on the context menu. Or, select the project node and press Alt+Enter.

  3. Choose Build, and go to the Errors and warnings subsection.

  4. In the Suppress warnings or Suppress specific warnings box, specify the error codes of the warnings that you want to suppress, separated by semicolons. For a list and descriptions of warning codes, see C# Compiler Messages.

  5. Rebuild the solution.
    :::moniker-end
    :::moniker range=»<=vs-2019″

  6. In Solution Explorer, choose the project in which you want to suppress warnings.

  7. Right-click on the project node, and choose Properties on the context menu. Or, select the project node and press Alt+Enter.

  8. Choose the Build page or section, and if you’re in the current UI, open the Errors and warnings subsection.

  9. In the Suppress warnings or Suppress specific warnings box, specify the error codes of the warnings that you want to suppress, separated by semicolons. For a list and descriptions of warning codes, see C# Compiler Messages.

  10. Rebuild the solution.
    :::moniker-end

[!NOTE]
Some warnings can’t be suppressed. For a list of those, see NoWarn compiler option.

Suppress specific warnings for C++

Use the Configuration Properties property page to suppress specific warnings for C++ projects.

  1. In Solution Explorer, choose the project or source file in which you want to suppress warnings.

  2. On the menu bar, choose View > Property Pages.

  3. Choose the Configuration Properties category, choose the C/C++ category, and then choose the Advanced page.

  4. Perform one of the following steps:

    • In the Disable Specific Warnings box, specify the error codes of the warnings that you want to suppress, separated by a semicolon.

    • In the Disable Specific Warnings box, choose Edit to display more options.

  5. Choose the OK button, and then rebuild the solution.

Suppress warnings for Visual Basic

You can hide specific compiler warnings for Visual Basic by editing the .vbproj file for the project. To suppress warnings by category, you can use the Compile property page. For more information, see Configure warnings in Visual Basic.

To suppress specific warnings for Visual Basic

This example shows you how to edit the .vbproj file to suppress specific compiler warnings.

  1. In Solution Explorer, choose the project in which you want to suppress warnings.

  2. On the menu bar, choose Project > Unload Project.

  3. In Solution Explorer, open the right-click or shortcut menu for the project, and then choose Edit <ProjectName>.vbproj.

    The XML project file opens in the code editor.

  4. Locate the <NoWarn> element for the build configuration you’re building with, and add one or more warning numbers as the value of the <NoWarn> element. If you specify multiple warning numbers, separate them with a comma.

    The following example shows the <NoWarn> element for the Debug build configuration on an x86 platform, with two compiler warnings suppressed:

    <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
        <PlatformTarget>x86</PlatformTarget>
        <DebugSymbols>true</DebugSymbols>
        <DebugType>full</DebugType>
        <Optimize>false</Optimize>
        <OutputPath>binDebug</OutputPath>
        <DefineDebug>true</DefineDebug>
        <DefineTrace>true</DefineTrace>
        <ErrorReport>prompt</ErrorReport>
        <NoWarn>40059,42024</NoWarn>
        <WarningLevel>1</WarningLevel>
      </PropertyGroup>

    [!NOTE]
    .NET Core projects do not contain build configuration property groups by default. To suppress warnings in a .NET Core project, add the build configuration section to the file manually. For example:

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp2.0</TargetFramework>
        <RootNamespace>VBDotNetCore_1</RootNamespace>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
        <NoWarn>42016,41999,42017</NoWarn>
      </PropertyGroup>
    </Project>
  5. Save the changes to the .vbproj file.

  6. On the menu bar, choose Project > Reload Project.

  7. On the menu bar, choose Build > Rebuild Solution.

    The Output window no longer shows the warnings that you specified.

For more information, see the /nowarn compiler option for the Visual Basic command-line compiler.

Suppress warnings for NuGet packages

In some cases, you may want to suppress NuGet compiler warnings for a single NuGet package, instead of for an entire project. The warning serves a purpose, so you don’t want to suppress it at the project level. For example, one of the NuGet warnings tells you that the package may not be fully compatible with your project. If you suppress it at the project level and later add an additional NuGet package, you would never know if it was producing the compatibility warning.

To suppress a specific warning for a single NuGet package

  1. In Solution Explorer, select the NuGet package you want to suppress compiler warnings for.

    :::moniker range=»vs-2019″
    Screenshot of NuGet package in Solution Explorer.
    :::moniker-end
    :::moniker range=»>=vs-2022″
    Screenshot of NuGet package in Solution Explorer.
    :::moniker-end

  2. From the right-click or context menu, select Properties.

  3. In the Suppress warnings box of the package’s properties, enter the warning number you want to suppress for this package. If you want to suppress more than one warning, use a comma to separate the warning numbers.

    :::moniker range=»vs-2019″
    NuGet package properties
    :::moniker-end
    :::moniker range=»>=vs-2022″
    Screenshot of NuGet package properties
    :::moniker-end

    The warning disappears from Solution Explorer and the Error List. In the project file, the NoWarn property is set.

     <PackageReference Include="NuGet.Build.Tasks.Pack" Version="6.2.0">
       <PrivateAssets>all</PrivateAssets>
       <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
       <NoWarn>NU5104</NoWarn>
     </PackageReference>

See also

  • Walkthrough: Build an application
  • How to: View, save, and configure build log files
  • Compile and build

I’m using exceptions to validate a control’s input in Silverlight 4. When I throw an invalid input exception, VS 2010 displays the popup and stops the program. I ignore this and resume the program, and everything continues fine (since the exception is used to signal a validation error.) Is there a way to mark that one exception as ignored?

I’m following this tutorial.

Jean-Bernard Pellerin's user avatar

asked Sep 10, 2010 at 21:43

Nick Heiner's user avatar

Nick HeinerNick Heiner

118k187 gold badges474 silver badges698 bronze badges

5

Debug -> Exceptions -> Uncheck

answered Sep 10, 2010 at 21:49

Jean-Bernard Pellerin's user avatar

1

Menu, Debugger, Exceptions…

In that dialog, you can remove the checkmark in the ‘thrown’ column for one exception, of for a whole namespace. You can add your own. etc.etc.

answered Sep 10, 2010 at 21:49

1

I got [System.Diagnostics.DebuggerHidden()] to work if I also selected

Debug > Options > Debugging > General > Enable Just My Code (Managed only).

I access the Excel object model a lot, and I really like to be able to run the debugger and catching all exceptions, since my code normally is exception less. However, the Excel API throws a lot of exceptions.

// [System.Diagnostics.DebuggerNonUserCode()]  works too
[System.Diagnostics.DebuggerHidden()]
private static Excel.Range TrySpecialCells(Excel.Worksheet sheet, Excel.XlCellType cellType)
{
    try
    {
        return sheet.Cells.SpecialCells(cellType);
    }
    catch (TargetInvocationException)
    {
        return null;
    }
    catch (COMException)
    {
        return null;
    }
}

bluish's user avatar

bluish

26.1k27 gold badges120 silver badges179 bronze badges

answered May 7, 2011 at 8:27

Mattias's user avatar

1

When you run Visual Studio in debug mode, there are Exception Setting on the bottom tool bar. Once you click it, there are all type exceptions. Uncheck exceptions that you want. For the Custom exception you made for this project, they are located in Common Language Runtime Exceptions, at very bottom. Hope this helpful.

answered Jul 9, 2018 at 16:16

plasma's user avatar

plasmaplasma

2873 silver badges12 bronze badges

You can disable some throw block by surrounding in the block

#if !DEBUG
       throw new Exception();
/// this code will be excepted in the debug mode but will be run in the release 
#endif

answered Sep 10, 2010 at 22:04

Pomoinytskyi's user avatar

1

Putting this above the property that throws the exception seems like it should work but apparently doesn’t:
[System.Diagnostics.DebuggerHidden()]:

    private String name;

    [System.Diagnostics.DebuggerHidden()]
    public String Name
    {
        get
        {
            return name;
        }
        set
        {
            if (String.IsNullOrWhiteSpace(value))
            {
                throw new ArgumentException("Please enter a name.");
            }
        }
    }

answered Oct 3, 2010 at 16:56

Nick Heiner's user avatar

Nick HeinerNick Heiner

118k187 gold badges474 silver badges698 bronze badges

From Visual Studio 2015 onward there is an Exception Settings window for this.

Debug > Windows > Exception Settings

answered Jan 17, 2018 at 19:30

Felix's user avatar

FelixFelix

3,7135 gold badges34 silver badges52 bronze badges

  • Remove From My Forums
  • Question

  • Hello:
    I have some C# .net code using Puppeteer, most of the time, it works well.  But sometimes, I see some errors, like the following:
    PuppeteerSharp.PuppeteerException
      HResult=0x80131500
      Message=Protocol error (Runtime.callFunctionOn): Session closed. Most likely the Page has been closed.Close reason: Target.detachedFromTarget
    As I just want to ignore this kind of error, so I write some code like this:

    try
    {
    do something in C#
    }
    catch (PuppeteerException ex)
    {
    Console.Write(ex.Message);
    }

    My code worked before when I used VS 2019 Version 16.1; 16.2; but now, I am using VS 2019 Version 16.3.2
    The above code simply not working in Debug mode, the program always stops at the catch statement.
    I want to setup the exception setting to continue in this case, but failed.
    I searched around, most of the articles about this issue seem just tell me how to break on this case, which is rather 
    narrow-minded, I just want to continue as this kind of error is not important.
    Please advice on how to change the Exception Settings in Visual Studio 2019 Version 16.3.2 to continue when the exception is handled by user.  Not to break at all!
    Thanks,

Answers

  • Hello:

    I seemed to find one solution, as the exception happened again, I un-check break on this type of exception, so my program can continue.  VS 2019 version 16.3.2 seems to remember what I did with the exception settings, so until now, it didn’t break again
    at the same point.

    But I still think VS 2019 the newest version needs better documents on how to handle this kind of situation, not let the developers to guess what could happen.

    • Proposed as answer by

      Monday, October 7, 2019 2:35 AM

    • Marked as answer by
      zydjohn
      Tuesday, October 8, 2019 9:49 PM

In Visual Studio, I can select the «Treat warnings as errors» option to prevent my code from compiling if there are any warnings. Our team uses this option, but there are two warnings we would like to keep as warnings.

There is an option to suppress warnings, but we DO want them to show up as warnings, so that won’t work.

It appears that the only way to get the behavior we want is to enter a list of every C# warning number into the «Specific warnings» text box, except for the two we want treated as warnings.

Besides the maintenance headache, the biggest disadvantage to this approach is that a few warnings do not have numbers, so they can’t be referenced explicitly. For example, «Could not resolve this reference. Could not locate assembly ‘Data….'»

Does anyone know of a better way to do this?


Clarifying for those who don’t see immediately why this is useful. Think about how most warnings work. They tell you something is a little off in the code you just wrote. It takes about 10 seconds to fix them, and that keeps the code base cleaner.

The «Obsolete» warning is very different from this. Sometimes fixing it means just consuming a new method signature. But if an entire class is obsolete, and you have usage of it scattered through hundreds of thousands of lines of code, it could take weeks or more to fix. You don’t want the build to be broken for that long, but you definitely DO want to see a warning about it. This isn’t just a hypothetical case—this has happened to us.

Literal «#warning» warnings are also unique. I often want to check it in, but I don’t want to break the build.

Code Focused

Hide Compiler Warnings in Your Spare Time

Learn how to keep new code-style warnings from filling up your formerly pristine Visual Studio Error List panel.

As Microsoft .NET Framework languages have grown in functionality, they’ve started tossing out compiler warnings like your development life depended on it. Messages about unused variables can sometimes help locate esoteric bugs. But new code-style warnings, such as whether your variables begin with capital letters, can easily fill up the formerly pristine Visual Studio Error List panel.

Of course, it’s always best to address the more meaningful warnings as quickly as possible. But if there are situations where you need to keep the questionable code as it is, and you don’t want to see the annoying warning message hanging around, Visual Studio offers a few different ways to suppress these messages, on scales from a single source line up to your entire project.

Consider, as an example, an asynchronous method that lacks an embedded await statement:

private async Task DoSomeWork()
{
  // ----- This method lacks an await statement, and therefore
  //       generates C# compiler warning CS1998.
}

Such C# code will add warning CS1998 to your Visual Studio experience, as shown in Figure 1.

[Click on image for larger view.]
Figure 1. Missing Await Statement Warning

The Code column in the Error List panel identifies the specific warning identity. If you want to hide a particular warning code across your entire project, open the overall properties through the Project | Properties menu command, and when the properties appear, select the Build page. The Suppress Warnings box on that page accepts a semicolon-delimited list of codes. Entering CS1998 in that field (see Figure 2) prevents the compiler from reporting that warning project-wide.

[Click on image for larger view.]
Figure 2. Project-Level Warning Suppression

If your warning-suppression needs are a bit more targeted, use the C# language #pragma statement to hide messages within a code file or block of source. The «warning disable» version of the statement, when paired with a comma-delimited list of codes, disables those codes for the remainder of that file’s processing:

#pragma warning disable CS1998

Leave off the list of codes to disable all warnings. If you want to reactivate the warnings later in the file, use the «warning restore» version of the statement instead. When used together, the two variations of the #pragma statement let you limit warning hiding to specific code lines:

#pragma warning disable CS1998 // Warning suppressed from here
private async Task DoSomeWork()
#pragma warning restore CS1998 // Warning recognized from here
{
}

If typing these statements is more than your fingers are willing to do, right-click on the warning message in the Error List panel and choose the Suppress | In Source command from the shortcut menu that appears. This action will surround the warning-laden line with the relevant #pragma statements.

Yet another way to disable warnings involves the SuppressMessage attribute, found in the System.Diagnostics.CodeAnalysis namespace. When applied to a method or other relevant code element, the attribute deactivates the indicated warning in a more object-centric manner:

// ----- Assumes: using System.Diagnostics.CodeAnalysis;
[SuppressMessage("Compiler", "CS1998")]
private async Task DoSomeWork()
{
}

I determined the first argument passed into the SuppressMessage attribute, «Compiler,» by turning on the Category column in the Error List panel and copying the text that appears for that warning. There are other options included with the attribute that let you narrow down the focus to specific code features. Microsoft recommends that you use SuppressMessage sparingly. Whereas #pragma does its work early in the compilation process and then says goodbye, the suppression attribute adds content to your final assembly, leading to attribute bloat or worse.

The MSDN documentation (such as this for C#) lists many of the error and warning codes you might encounter, allowing you to be proactive in your warning-suppression activities. But because one major goal of programming is to fix problems instead of hiding them, it’s probably best to act on individual messages as they pop up in the Error List panel. Let this be a warning to you.

About the Author


Tim Patrick has spent more than thirty years as a software architect and developer. His two most recent books on .NET development — Start-to-Finish Visual C# 2015, and Start-to-Finish Visual Basic 2015 — are available from http://owanipress.com. He blogs regularly at http://wellreadman.com.

Понравилась статья? Поделить с друзьями:
  • Как игнорировать ошибку в visual studio
  • Как избавится от ошибки dns
  • Как зовут человека который исправляет ошибки
  • Как игнорировать ошибку в unity
  • Как избавится от ошибки 502