c# – I need a code that gives the AccessViolationException error

Question:

My teacher went through a series of exercises and in them I need to create code to give the AccessViolationException error. But I'm not able to create a code that gives this error (I'm not wanting to handle the error).

I need something to insert into the try .

try{
    //código que retorna o erro 
}catch(AccessViolationException ex){
    Console.WriteLine(ex);
}

Answer:

It's simple:

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

See working on ideone . And in .NET Fiddle . Also posted on GitHub for future reference .

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

There is a question on the OS that deals with this with an answer from someone who understands it well, but I don't know if it works.

Scroll to Top