What is a throw

Can someone explain to me the use of throw in exception handling? What happens when I make an exception?

+3
source share
5 answers

This means throwing an exception. When you “throw” an exception, you say “something went wrong, here are some details.”

Then you can “catch” the “thrown” exception so that your program can correctly degrade, instead of mistakenly dying.

+13
source

An “throw” of an exception is what triggers the entire process of handling exceptions.

. , .

, "" , "catch". catch catch ( "" ), catch.

// Do some stuff, an exception thrown here won't be caught.
try
{
  // Do stuff
  throw new InvalidOperationException("Some state was invalid.");
  // Nothing here will be executed because the exception has been thrown
}
catch(InvalidOperationException ex) // Catch and handle the exception
{
  // This code is responsible for dealing with the error condition
  //   that prompted the exception to be thrown.  We choose to name
  //   the exception "ex" in this block.
}
// This code will continue to execute as usual because the exception
//   has been handled.
+6

, , - , . , - ( ).

, , catch, , . finally , , ( ) , , , .

+3

. , , , .

, - , .

+1

. throw.

  • ,

    if(inputVal < 0)
    {
        throw new LessThanZeroCustomException("You cannot enter a value less than zero");
    }
    

    , LessThanZeroCustomException. , Custom , . ,

  • , . - . , , . , try ... catch . !

In short, it throwmeans "I found an exceptional condition that I cannot handle, so I let the person using this code know by throwing an exception."

+1
source

Source: https://habr.com/ru/post/1703617/


All Articles