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

This question comes up as one of the top 3 hits for the Google search for «how to suppress -Wunused-result in c++», so I’m adding this answer here since I figured it out and want to help the next person.

In case your warning/error is -Wunused (or one of its sub-errors) or -Wunused -Werror only, the solution is to cast to void:

For -Wunused or one of its sub-errors only1, you can just cast it to void to disable the warning. This should work for any compiler and any IDE for both C and C++.

1Note 1: see gcc documentation here, for example, for a list of these warnings: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html, then search for the phrase «All the above -Wunused options combined» and look there for the main -Wunused warning and above it for its sub-warnings. The sub-warnings that -Wunused contains include:

  • -Wunused-but-set-parameter
  • -Wunused-but-set-variable
  • -Wunused-function
  • -Wunused-label
  • -Wunused-local-typedefs
  • -Wunused-parameter
  • -Wno-unused-result
  • -Wunused-variable
  • -Wunused-const-variable
  • -Wunused-const-variable=n
  • -Wunused-value
  • -Wunused = contains all of the above -Wunused options combined

Example of casting to void to suppress this warning:

// some "unused" variable you want to keep around
int some_var = 7;
// turn off `-Wunused` compiler warning for this one variable
// by casting it to void
(void)some_var;  // <===== SOLUTION! ======

For C++, this also works on functions which return a variable marked with [[nodiscard]]:

C++ attribute: nodiscard (since C++17)
If a function declared nodiscard or a function returning an enumeration or class declared nodiscard by value is called from a discarded-value expression other than a cast to void, the compiler is encouraged to issue a warning.
(Source: https://en.cppreference.com/w/cpp/language/attributes/nodiscard)

So, the solution is to cast the function call to void, as this is actually casting the value returned by the function (which is marked with the [[nodiscard]] attribute) to void.

Example:

// Some class or struct marked with the C++ `[[nodiscard]]` attribute
class [[nodiscard]] MyNodiscardClass 
{
public:
    // fill in class details here
private:
    // fill in class details here
};

// Some function which returns a variable previously marked with
// with the C++ `[[nodiscard]]` attribute
MyNodiscardClass MyFunc()
{
    MyNodiscardClass myNodiscardClass;
    return myNodiscardClass;
}

int main(int argc, char *argv[])
{
    // THE COMPILER WILL COMPLAIN ABOUT THIS FUNCTION CALL
    // IF YOU HAVE `-Wunused` turned on, since you are 
    // discarding a "nodiscard" return type by calling this
    // function and not using its returned value!
    MyFunc();

    // This is ok, however, as casing the returned value to
    // `void` suppresses this `-Wunused` warning!
    (void)MyFunc();  // <===== SOLUTION! ======
}

Lastly, you can also use the C++17 [[maybe_unused]] attribute: https://en.cppreference.com/w/cpp/language/attributes/maybe_unused.

In debug mode, if there is an error in our application when we press F5 to start debugging, a dialog appears with the warning: «Your program has an error. Do you want to run your last modified program?» or something like this.

I want to enable or disable this dialog.

How can I do this?

Benjol's user avatar

Benjol

63.5k54 gold badges186 silver badges266 bronze badges

asked Jan 17, 2011 at 10:20

Tavousi's user avatar

3

You can turn that prompt on/off in your Visual Studio settings:

  1. From the «Tools» menu, select «Options».
  2. In the dialog that appears, expand «Projects and Solutions», and click «Build and Run».
  3. On the right side, you’ll see a combo box labeled «On Run, when build or deployment errors occur».

    • If you want to disable the message box, select either «Do not launch» or «Launch old version» (which will launch the old version automatically).
    • If you want to enable the message box, select «Prompt to launch» which will ask you each time.

   VS "Build and Run" Options

Of course, as people have suggested in the comments, this means that your code has errors in it somewhere that are preventing it from compiling. You need to use the «Error List» to figure out what those errors are, and then fix them.

answered Jan 17, 2011 at 10:29

Cody Gray - on strike's user avatar

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.

  • 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

Возможно, вам также будет интересно:

  • Visual studio журнал ошибок
  • Visual studio выдает ошибку не удается запустить программу
  • Visual studio scanf ошибка
  • Visual studio just in time debugger ошибка как исправить
  • Visual studio installer произошла неизвестная ошибка приносим свои извинения windows 7

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии