I need a code that gives the error Accessviolationexception

Asked

Viewed 208 times

3

My teacher passed a series of exercises and in them I need to create a code to give the error AccessViolationException. However I am not able to create a code that of this error (I am not willing to make the error treatment).

I need something to insert into the try.

try{
    //código que retorna o erro 
}catch(AccessViolationException ex){
    Console.WriteLine(ex);
}
  • Gives a System.IO.Directory.DeleteDirectory("C:\\Windows\\System32"); and you’ll have a AccessViolationException (and other little surprises).

2 answers

6

It’s simple:

try {
    throw new AccessViolationException();
} catch (AccessViolationException ex){
    Console.WriteLine(ex);
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

I wasn’t in the question I couldn’t use throw. These fictitious rules are useless. The only utility I see to simulate the error is to do tests and this can be done with the throw.

There’s a question in the OS which deals with this in response from those who understand well, but I don’t know if it works.

  • I can’t use a throw

  • Look, technically, it’s not wrong.

2


The code below consistently generates a type exception AccessViolationException:

var ptr = new IntPtr(42);
Marshal.StructureToPtr(42, ptr, true);

That said, @Maniero’s response is correct. There is no aspect of throw new AccessViolationException() which generates a different behaviour.

Source:
How to test Handling of Accessviolationexception

Browser other questions tagged

You are not signed in. Login or sign up in order to post.