Click here to Skip to main content
15,885,782 members
Everything / General Programming / Exceptions

Exceptions

exceptions

Great Reads

by Giovanni Scerra
Patterns to prevent null reference exceptions
by Jasper Lammers
A method to easily toggle the way exceptions are being handled (either being thrown or handled by custom code), while still conserving the stack trace when exceptions are not being thrown.
by Marco Bertschi
This tip presents an easy way of verbosely converting an exception and its inner exceptions to a string in order to get access to all details.
by Amogh Natu
This tip provides one solution to the exception "Configuration system failed to initialize" in C#

Latest Articles

by Dev Leader
Secret of Task EventHandlers
by Bruno van Dooren
Symantec can cause valid applications to crash and be gone without a trace
by Mark Pelf
We explain how to debug and get more information on the generic Exception “Failed to enable constraints.
by Greg Utas
Keeping a program running when it would otherwise abort

All Articles

Sort by Score

Exceptions 

26 Feb 2015 by Giovanni Scerra
Patterns to prevent null reference exceptions
3 Jan 2018 by Jasper Lammers
A method to easily toggle the way exceptions are being handled (either being thrown or handled by custom code), while still conserving the stack trace when exceptions are not being thrown.
1 Apr 2017 by Marco Bertschi
This tip presents an easy way of verbosely converting an exception and its inner exceptions to a string in order to get access to all details.
1 Mar 2014 by Amogh Natu
This tip provides one solution to the exception "Configuration system failed to initialize" in C#
4 Nov 2010 by Nish Nishant
The problem in that code is that row.Cells[ "Quantity" ].Value can be null, but you call ToString on that without checking for that.Change:string.IsNullOrEmpty( row.Cells[ "Quantity" ].Value.ToString() )tostring.IsNullOrEmpty( row.Cells[ "Quantity" ].Value as String)Btw...
21 Oct 2011 by Mehdi Gholam
Try this :if(n!="") score += int.Parse(n);
17 Jun 2022 by Mircea Neacsu
C++ thread objects and their use
16 Mar 2017 by Arthur Minduca
How to handle faults in WCF without declaring them explicitly
30 Dec 2010 by Dave Kreskowiak
Im just guessing because you didn't supply the exception message, but it sounds like you're opening the file while the process that is writing to it still has it open.Modify your code so that it retrys the file operations. If it gets an exception, wait a second or two and go back and try it...
20 Jun 2012 by Sergey Alexandrovich Kryukov
A static collection is a typical source of a "memory leak by design". In .NET, you are more or less protected from the casual memory leaks, because you don't have to clean up memory after every operation you use it; the Garbage Collector (GB) takes care about it. Despite of the common believe,...
20 Jun 2012 by DaveyM69
What sort of data are you storing in your list? I have used (in testing) extremely large lists without issue.The size of any item in .NET is limited to 2GB. The maximum value for a lists capacity is 2147483647 so theoretically you could store that many bytes in the list and be right on the...
26 Jun 2015 by OriginalGriff
Because the For Each loop is altering the target of the loop - which is a no-no!The for loop modifies an index value each time round, so it's fine to alter the content of the Keys collection - or even to delete them. That doesn't affect anything, because the Count of the number of objects...
2 Apr 2020 by Richard Deeming
I suspect the problem is that you are storing your OleDbCommand object in a class-level field, and reusing it across methods. Change your code to create the command instance when you need it, and wrap it in a Using block, and your error will...
31 Jan 2011 by Nick Alexeev
12 Apr 2011 by OriginalGriff
If you don't throw an exception, then there is no standard mechanism for error reporting. You could provide one - before exceptions that was the norm - just provide your method with a bool or int return value.Exceptions are a better solution though: if a parameter is outside the allowed...
12 Apr 2011 by Sergey Alexandrovich Kryukov
You should never use "error codes" in replacement of exceptions. Invention of exceptions made all non-exception method obsolete. It needs understanding of exception mechanism which goes above the regular paradigm of methods and calls: it jumps over the stack during propagation. Many do not...
8 Jun 2011 by OriginalGriff
Change comm = new OdbcCommand("select * from utilisateur where login=?", cn); comm.Parameters.Add("login", login.Text);To comm = new OdbcCommand("select * from utilisateur where login=@LI", cn); comm.Parameters.Add("@LI",...
8 Jun 2011 by Sandeep Mewara
Adding to other answer:" System.NullReferenceException: Object reference not set to an instance of an object."This simply means that you are trying to access a property of an object that is null. Using Visual Studio DEBUGGER will tell you exact line and the object that is null and thus...
21 Oct 2011 by André Kraak
The solution given by Mehdi Gholam works, but this alternative also solves your problem.protected int Checkscore(Node x) { char[] delimiter = {';'}; string[] numbers = x.GetProperty("answers").Value.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); ...
3 Nov 2012 by Grant Harmer
Managing exceptions when consuming WCF services via the BizTalk ESB Toolkit
9 Jul 2013 by nv3
Note that Microsoft differentiates between C++ exceptions (as defined by the ANSI standard) and Structured Exceptions (as defined by MS and independent of C++). An access violation produces that latter one.To catch structured exceptions you can use the __try / __finally mechanism as...
22 Jul 2013 by Sergey Alexandrovich Kryukov
You can guarantee that you never run into this exception. As you consume more and more memory, you can always exceed your budget.However, in your case, you simply never need so many records at once. No user needs to see that many. You need to show limited portion of data at once, usually...
2 Aug 2013 by Ron Beyer
Quote:WindowsFormsApplication6...
16 Aug 2013 by pasztorpisti
This is basically a NULL pointer exception. Its 0x10 and not zero because you are using the NULL pointer as a pointer to a struct/class and you are trying to access a member of that struct/class that is on offset 0x10 inside the struct/class. Still it is a NULL pointer "exception".The bug is...
23 Jan 2014 by OriginalGriff
First off, don't try to save anything in the root folder of any drive, and particularly not in the root of your boot drive: From Vista onwards it takes special permission to avoid virus tampering, and it will not get any easier.Second, if this is really a ASP.NET application, you will almost...
23 Jan 2014 by OriginalGriff
Take off the OpenOrCreate, which discards any previous file content.By preference, replace the whole FileStream code with File.AppendAllText[^] - it opens teh file, appends the new text, and closes the file again in a single line. And it doesn't leave a FileStream object (fs1) sitting there...
8 Sep 2014 by cogi83
A SW to send your WAN IP and other info via email
10 Sep 2014 by Franz.net
Hello,it's been a while since i last posted a message on this site. Usually i can find what i'm looking for, but not today.What i'm trying to find is an easy way to centralize exception messages in a .Net application. So the whole exception handling is taken care of, but currently the...
11 Nov 2014 by Dave Clemmer
Using the Microsoft patterns and practices Semantic Logging Application Block (SLAB) to both structure your logging information and decouple how you choose to log from your application code that initiates logging related events. Plus, a Loggly listener is included that you can use to log messages.
31 Jan 2017 by #realJSOP
Set the project's target to x86.
14 Oct 2021 by Dave Kreskowiak
Look at what you appear to be doing: String phoneNumber = ""; String textMessage = ""; FileInputStream excelFile = new FileInputStream(file); Path sourcePath = Paths.get(String.valueOf(file)); Path targetPath =...
7 Sep 2022 by Bruno van Dooren
Symantec can cause valid applications to crash and be gone without a trace
21 Jul 2010 by Sandeep Mewara
Error is in this part of code:for (int i = 1; i
25 Mar 2011 by #realJSOP
try{ string[] files = Directory.GetFiles("C:\MyDir", "*.*", SearchOption.AllDirectories); // do something with your file array}catch (UnauthorizedAccessException){ // this eats the exception but it will still stop}catch (Exception ex){ // you can handle all...
20 Jun 2011 by CPallini
Have a look at the article: Microsoft Visual C++ and Win32 structured exception handling[^].
20 Jun 2011 by Niklas L
I don't know if this will help you, but you can make the VS debugger break when an exception is thrown. In the Debug -> Exceptions Dialog, you can select which exceptions to handle this way.This obviously only works when debugging. If you want to be able to trace to a log file, follow Mr...
6 Nov 2011 by RaisKazi
Try by calling one service at a time. Check are you able to connect to both your Web Services one at a time. From the Exception details it sounds to be your Service is unreachable from the Device.You may also post your Question on Android Developers...
14 May 2012 by Prasad_Kulkarni
Please refer following some nice articles of CP:Exception Handling Best Practices in .NET[^]Using Try... Catch..., Finally![^]Also refer this:The finally Block[^]Exception Handling for C# Beginners[^]Exception handling in C# and ASP .Net[^]
10 Oct 2012 by OriginalGriff
If you are trying to follow the instructions on how to get your system up and running with Eclipse, you may get an error when installing ADT
12 Oct 2012 by Stefan_Lang
A simple way to clarify the requirements of your exception class, is to look at each throw statement, and imagine it were a return statement instead. In this case, all throw statements look the same: they "return" an object of a class called SocketException, and initialize it with a single...
3 Nov 2012 by chaau
It is right in the MSDN[^]. See the Remarks section close to the end. If a console process is being debugged and CTRL+C signals have not been disabled, the system generates a DBG_CONTROL_C exception. This exception is raised only for the benefit of the debugger, and an application should...
4 Apr 2013 by jgauffin
This post will discuss what exceptions are.
22 Apr 2013 by Brady Kelly
A handy way to raise an exception without having to call String.Format for the exception message
17 Oct 2013 by Javier Tirado Pampín
This article talks about how to solve the filter problem in Telerik MVC Extensions control suite
9 Jan 2014 by bowlturner
throw new Exception(v.ToString()); if it's C#
23 Jan 2014 by phil.o
The most obvious is that C:\Error.txt is not a directory, but a file. So your catch block should be more like:catch (Exception ex) { string path = @"C:\Error.txt"; // file path using (StreamWriter sw = new StreamWriter(path, true)) { // If file exists, text will be appended ;...
23 Jan 2014 by Karthik_Mahalingam
try thisstring path ="D:\\Error.txt"; File.AppendAllLines(path , new string[] { string.Format("Message: {0}{1}StackTrace :{2}{1}Date :{3}{1}-----------------------------------------------------------------------------{1}", ex.Message, Environment.NewLine,...
10 Sep 2014 by CPallini
Possibly this Code Project article fits your needs: "Exception Handling Best Practices in .NET"[^].
23 Oct 2014 by TorstenH.
So I took the effort of looking through your code.Are you using a proper IDE? Does not look like.PLEASE USE ECLIPSE OR NETBEANS. Both are free. Both would have told you about the mess you're creating.public class dbsrv extends HttpServlet{ // open class public void...
6 Mar 2016 by Jochen Arndt
Just check if splitting was possible. If there was no ':' character, the string is not splitted and the list contains only one element (the original string):if (TextFields.count() == 1) throw;But in your case there is no need to use exceptions because you are detecting and handling the...
26 Jun 2016 by OriginalGriff
Use the debugger.Set a breakpoint at the line:myMib.loadDirectoryMib(Environment.GetFolderPath(Environment.SpecialFolder.System ));And step into your method.Follow the code through step by step, and see what it is doing.The most likely thing is that it's trying to recursively load files,...
5 Dec 2016 by #realJSOP
Put a try/catch block around the call to that method, and in the catch section, display the exceptions message property to the user.
26 Apr 2018 by Jochen Arndt
Are you sure that the error occurs when adding the workbook? I guess it is happening when adding the sheet with xlWorkSheet = xlWorkBook.Sheets.Add("Sheet1") The first parameter specifies the sheet before which the new sheet is added (see Worksheets.Add method ...
20 Jun 2018 by F-ES Sitecore
try { // your code here } catch(Exception exp) { // you can log the exception here or simply do nothing } finally { // the finally block is optional but you can put code you want to happen here after an exception occurs if you want } That answers your question but it isn't going to...
12 Apr 2021 by Patrice T
Quote: The instructions for this assignment are unclear and was not given example code Since the job of programming is about creating algorithms/programs, your sentence is weird. It is like saying that you are a cook dying from starvation...
2 Jan 2022 by Luc Pattyn
it looks like bmp is null due to resourceId being zero. And you did not show any code that sets resourceId...
15 Jul 2022 by Mark Pelf
We explain how to debug and get more information on the generic Exception “Failed to enable constraints.”
24 Nov 2023 by Graeme_Grant
The best solution, IMHO, would be to create a custom log provider. You can then handle the logging as the log entries are added. I wrote an article for a custom Log Viewer control that has a custom Log Provider, one for each of the 4 common...
23 Jun 2010 by Wonixen
I have an out of proc COM server implemented in an exe. one of the COM method raise an exception instead of returning an HRESULTex:HRESULT ComObject::Fubar(){ RaiseException(1,0,0,0,NULL); return S_OK;}in my client, after calling Fubar(), sometime the HRESULT is positive,...
21 Jul 2010 by Abhinav S
Check if any of the values in the cells are null.If they are you need to modify your code to check for null conditions before using ToString().
17 Aug 2010 by Niklas L
In the Debug | Exceptions dialog, you can specify how exceptions should be treated by the debugger. You can chose to break into the debugger when a specific exception is thrown.So if you know what type to look for, that could be one way of doing it.
4 Feb 2011 by Nick Alexeev
My m_ctrlContainer was a "built-in" panel of a SplitContainer (as in splitContainer1.Panel1). That's why the collection was read-only. Well duh.This code had pointed me in the right direction.m_ctrlContainer.Parent.Controls.Remove(m_ctrlContainer); // threw exception “Collection is read...
15 Mar 2011 by Sergey Alexandrovich Kryukov
Answering to the reply about exception:Here is the advice what to start with. The problem is that you don't provide enough information about exception. Please see my directions:How do i make a loop that will stop when a scrollbar reaches the bottom[^]When i run an application an...
15 Mar 2011 by fjdiewornncalwe
Simple... Your endpoint is incorrect.On your computer it works because the endpoint is local
15 Mar 2011 by Espen Harlinn
Markus is definitely on to something - that binding will not work for deployment.I'd also wrap the Grid1.ItemsSource = e.Result; in a try/catch block, like:void webclinet_GetRowsCompleted(object sender, GetRowsCompletedEventArgs e) { try { webclinet.GetRowsCompleted -=...
25 Mar 2011 by Sandeep Mewara
The current identity (OSM\ASPNET) does not have write access to 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'.Error statement is more than enough by itself. You need to provide write access security permissions to OSM\ASPNET on the folder or you can impersonate...
25 Mar 2011 by Dylan Morley
Use recursion rather than the SearchOption.AllDirectories value. e.g.http://www.dotnetperls.com/recursively-find-files[^]Or MSDN versionhttp://msdn.microsoft.com/en-us/library/07wt70x2.aspx[^]This way, you can just try-catch on any directories with permissions issues and...
28 Mar 2011 by CPallini
Well, you actually can do that: try { CStringArray ss; ss.RemoveAll(); ss.ElementAt(1); } catch(...) { AfxMessageBox("Get invalid element"); }You'll get the assertion just with DEBUG build. RELEASE build will not assert.
18 Apr 2011 by Aerryc
Using Rama Krishna Vavilala's article as a reference, I have been working on developing a data repository model for use at my orgnaization and, with one exception, it works as expected. I have included a simple version of the model that illustrates the issue.The question: Why do references...
15 Apr 2011 by Albin Abel
In a repository frameworks (which is usually for larger projects which need agile testing) usually the repository, business model, services and presentation all will be treated as separate projects. In domain driven design the business model is the core and independent and other layers above it...
22 May 2011 by fgoldenstein
Cannot open Microsoft Access database -> Exception message "unknown"
19 May 2011 by Peter_in_2780
Since Exception has what is effectively a copy constructor, you can do this:FileNotFoundException saveException = null;try { readfile(); // might throw FileNotFoundException} catch (FileNotFoundException fnfEx) { saveException = new FileNotFoundException(fnfEx);} finally { ...
10 Jun 2011 by Sander Rossel
Read this[^]. Small, but effective answer on StackOverflow. Hope it helps.
20 Jun 2011 by Peter Weyzen
A colleague of mine (on a mac) has some code which can hijack the "throw" in order to produce a stack trace at the point the exception is thrown.I was wondering if there were some pre-built stuff for windows to accomplish the same?
21 Jun 2011 by EriBeh
Hello,I sometimes get an exception from Connecting to a webservice. I could catch the exception like this:catch (System.ServiceModel.Security.MessageSecurityException ex)if (ex.ToString().ToLower().Contains("security timestamp"))but this is not working on foreign language versions of...
21 Jun 2011 by Timberbird
I guess you want to use exception's message because there are numerous possible exceptions of exactly the same class but with other messages, and you want to set specific procession for only this one, thrown by particular method from the inner depths of .NET assemblies? Well, seems like a tough...
21 Jun 2011 by BobJanova
Log the exception when it occurs. The standard ToString of an exception includes the exception type.
6 Jul 2011 by Sergey Alexandrovich Kryukov
Testing anything for exceptions is a big abuse of the technology. Let exceptions go.What to do? Please find some recommendations in my past answers:How do i make a loop that will stop when a scrollbar reaches the bottom[^],When i run an application an exception is caught how to handle...
21 Jul 2011 by CGN007
Thanks for your time in advance !!I'm Getting the following error while printing in WPF. PrintTicket provider failed to retrieve PrintCapabilities. Win32 error: -2147418113Here is my Code to PrintprintDlg.PrintDocument(idpSource.DocumentPaginator, "Hello WPF Printing.");
22 Jul 2011 by Mark Salsbery
Maybe something useful here...PrintTicket provider failed to retrieve PrintCapabilities[^]Print the UserControl[^]
9 Aug 2011 by BlackJack99
Finally got it to work! followed the solution here: http://forums.silverlight.net/t/40770.aspx[^]seems like i only need to increase the size limit...
10 Aug 2011 by CGN007
I don't know what is exactly the problem,But something related to Printer.From Control Panel->Printers & Fax1.Right Click the Printer and take Printer preferences2.Change the Source property to 'Manual Feed'& Apply.(Initially it was'AutoSelect')3.Still got some error.4.Again me...
2 Sep 2011 by RaisKazi
Below link will give you details around System.OverflowException.OverflowException ClassMost probably your code throwing Exception on either of below lines.east_Count = Convert.ToInt32(cmd.ExecuteScalar());OReast_Count += Convert.ToInt32(cmd.ExecuteScalar());Debug your code and...
21 Oct 2011 by Wayne Gaylard
Have you tried Convert.ToInt32(n). I seem to have more luck with that than with int.Parse, especially when converting results from a database.
7 Dec 2011 by Anoop_Ravindran
Hi all,I have a .net 4.0 windows application which is migrated from .net 3.5. This windows application is using a third party DLL file (from Windows\system32\MyScanner.dll) which is used to connect with a scanner attached to the system through USB port. This application is working...
10 Dec 2011 by thatraja
Fix linkReceiving “Path 'OPTIONS' is forbidden.” Exception in ASP.NET website[^]
6 Jan 2012 by fjdiewornncalwe
Your item ItemTemplate needs to define how each record will be displayed.When you set your datasource to "gc" and databind it, the Eval in your ItemTemplate is going to check the gc object for a property named "gc" which of course it does not and that is why you get the error. Say, for...
10 Jan 2012 by Sergey Alexandrovich Kryukov
Oh, I see. The problem is that FindControl returns null. This is a big common mistake to use this method. Why? You have access to all your controls via the members which are explicitly declared.You can have a misspelling or something, and you compiler cannot detect a problem.—SA
23 Jan 2012 by OriginalGriff
They don't do it like that - they draw only the images that the user sees - at no time do they load 1000 images and hope it will work. The most they might do is load the image, take a small thumbnail of it, and unload the image. The thumbnails are then available for display as the user needs...
23 Jan 2012 by unknowndentified10111
In relation to OriginalGriff's answer, here is the code for resizing the images or creating thumbnails:public class Tools{ public static Image ResizeImage(Image imgToResize, Size size) { int sourceWidth = imgToResize.Width; int sourceHeight =...
11 Sep 2012 by John Bhatt
How can I block some website permanently like (facebook.com) and more social site on my employees computers
10 Jul 2012 by Sergey Alexandrovich Kryukov
Generally, I like the approaches where an exception is thrown. Re-throwing of the exception is also a good thing. Here you follow the exception-based "throw-and-forget" approach. So, I do not fully agree with Naerling: using TryParse is not always the best thing. Besides, as the name suggests,...
26 Sep 2012 by ♥…ЯҠ…♥
Crazy Visual studio, was suffering with that error for a while and finally decided to move my whole solution to new path (f:\ drive),from there I try to build and try to update the service.Where i am able to do that.Thanks for everyone who helped me so far.
1 Oct 2012 by OriginalGriff
You haven't set any of the parameters you specified in the command string: SqlCeCommand code_comm_two = new SqlCeCommand("SELECT transmission_code FROM vehicles WHERE make = @make AND model_name = @model AND model_year = @model_year AND engine_type = @engine_type", conn);You have...
3 Oct 2012 by Dave Kreskowiak
You can try locking all you want, but it's never going to work.You cannot use Excel Automation on a background thread. It must be kept on the startup thread.
22 Oct 2012 by dashingly
I had to check if value was null, but it only worked in the certain way: if (rng.Value2 != null){}
3 Nov 2012 by OriginalGriff
Um. I'm not surprised.Your code is effectivelyint j = 2;for (int i = 0; i
8 Nov 2012 by Nemonics
I am trying to implement NHibernate 3.2.2 updating application coded originally written with NHibernate 1.2.1. Needless to say, I have needed to make a number of changes just to successful ly compile the code. I am now stuck with the following exception that occurs when I attempt to read any...