Search Results

Search found 16333 results on 654 pages for 'exception safe'.

Page 1/654 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • One Exception to Aggregate Them All

    - by João Angelo
    .NET 4.0 introduced a new type of exception, the AggregateException which as the name implies allows to aggregate several exceptions inside a single throw-able exception instance. It is extensively used in the Task Parallel Library (TPL) and besides representing a simple collection of exceptions can also be used to represent a set of exceptions in a tree-like structure. Besides its InnerExceptions property which is a read-only collection of exceptions, the most relevant members of this new type are the methods Flatten and Handle. The former allows to flatten a tree hierarchy removing the need to recur while working with an aggregate exception. For example, if we would flatten the exception tree illustrated in the previous figure the result would be: The other method, Handle, accepts a predicate that is invoked for each aggregated exception and returns a boolean indicating if each exception is handled or not. If at least one exception goes unhandled then Handle throws a new AggregateException containing only the unhandled exceptions. The following code snippet illustrates this behavior and also another scenario where an aggregate exception proves useful – single threaded batch processing. static void Main() { try { ConvertAllToInt32("10", "x1x", "0", "II"); } catch (AggregateException errors) { // Contained exceptions are all FormatException // so Handle does not thrown any exception errors.Handle(e => e is FormatException); } try { ConvertAllToInt32("1", "1x", null, "-2", "#4"); } catch (AggregateException errors) { // Handle throws a new AggregateException containing // the exceptions for which the predicate failed. // In this case it will contain a single ArgumentNullException errors.Handle(e => e is FormatException); } } private static int[] ConvertAllToInt32(params string[] values) { var errors = new List<Exception>(); var integers = new List<int>(); foreach (var item in values) { try { integers.Add(Int32.Parse(item)); } catch (Exception e) { errors.Add(e); } } if (errors.Count > 0) throw new AggregateException(errors); return integers.ToArray(); }

    Read the article

  • Abstract exception super type

    - by marcof
    If throwing System.Exception is considered so bad, why wasn't Exception made abstract in the first place? That way, it would not be possible to call: throw new Exception("Error occurred."); This would enforce using derived exceptions to provide more details about the error that occurred. For example, when I want to provide a custom exception hierarchy for a library, I usually declare an abstract base class for my exceptions: public abstract class CustomExceptionBase : Exception { /* some stuff here */ } And then some derived exception with a more specific purpose: public class DerivedCustomException : CustomExceptionBase { /* some more specific stuff here */ } Then when calling any library method, one could have this generic try/catch block to directly catch any error coming from the library: try { /* library calls here */ } catch (CustomExceptionBase ex) { /* exception handling */ } Is this a good practice? Would it be good if Exception was made abstract? EDIT : My point here is that even if an exception class is abstract, you can still catch it in a catch-all block. Making it abstract is only a way to forbid programmers to throw a "super-wide" exception. Usually, when you voluntarily throw an exception, you should know what type it is and why it happened. Thus enforcing to throw a more specific exception type.

    Read the article

  • Distinguishing between .NET exception types

    - by Swingline Rage
    For the love of all things holy, how do you distinguish between different "exception flavors" within the predefined .NET exception classes? For example, a piece of code might throw an XmlException under the following conditions: The root element of the document is NULL Invalid chars are in the document The document is too long All of these are thrown as XmlException objects and all of the internal "tell me more about this exception" fields (such as Exception.HResult, Exception.Data, etc.) are usually empty or null. That leaves Exception.Message as the only thing that allows you to distinguish among these exception types, and you can't really depend on it because, you guessed it, the Exception.Message string is glocabilized, and can change when the culture changes. At least that's my read on the documentation. Exception.HResult and Exception.Data are widely ignored across the .NET libraries. They are the red-headed stepchildren of the world's .NET error-handling code. And even assuming they weren't, the HRESULT type is still the worst, downright nastiest error code in the history of error codes. Why we are still looking at HRESULTs in 2010 is beyond me. I mean if you're doing Interop or P/Invoke that's one thing but... HRESULTs have no place in System.Exception. HRESULTs are a wart on the proboscis of System.Exception. But seriously, it means I have to set up a lot of detailed specific error-handling code in order to figure out the same information that should have been passed as part of the exception data. Exceptions are useless if they force you to work like this. What am I doing wrong?

    Read the article

  • How safe is my safe rethrow?

    - by gustafc
    (Late edit: This question will hopefully be obsolete when Java 7 comes, because of the "final rethrow" feature which seems like it will be added.) Quite often, I find myself in situations looking like this: do some initialization try { do some work } catch any exception { undo initialization rethrow exception } In C# you can do it like this: InitializeStuff(); try { DoSomeWork(); } catch { UndoInitialize(); throw; } For Java, there's no good substitution, and since the proposal for improved exception handling was cut from Java 7, it looks like it'll take at best several years until we get something like it. Thus, I decided to roll my own: (Edit: Half a year later, final rethrow is back, or so it seems.) public final class Rethrow { private Rethrow() { throw new AssertionError("uninstantiable"); } /** Rethrows t if it is an unchecked exception. */ public static void unchecked(Throwable t) { if (t instanceof Error) throw (Error) t; if (t instanceof RuntimeException) throw (RuntimeException) t; } /** Rethrows t if it is an unchecked exception or an instance of E. */ public static <E extends Exception> void instanceOrUnchecked( Class<E> exceptionClass, Throwable t) throws E, Error, RuntimeException { Rethrow.unchecked(t); if (exceptionClass.isInstance(t)) throw exceptionClass.cast(t); } } Typical usage: public void doStuff() throws SomeException { initializeStuff(); try { doSomeWork(); } catch (Throwable t) { undoInitialize(); Rethrow.instanceOrUnchecked(SomeException.class, t); // We shouldn't get past the above line as only unchecked or // SomeException exceptions are thrown in the try block, but // we don't want to risk swallowing an error, so: throw new SomeException("Unexpected exception", t); } private void doSomeWork() throws SomeException { ... } } It's a bit wordy, catching Throwable is usually frowned upon, I'm not really happy at using reflection just to rethrow an exception, and I always feel a bit uneasy writing "this will not happen" comments, but in practice it works well (or seems to, at least). What I wonder is: Do I have any flaws in my rethrow helper methods? Some corner cases I've missed? (I know that the Throwable may have been caused by something so severe that my undoInitialize will fail, but that's OK.) Has someone already invented this? I looked at Commons Lang's ExceptionUtils but that does other things. Edit: finally is not the droid I'm looking for. I'm only interested to do stuff when an exception is thrown. Yes, I know catching Throwable is a big no-no, but I think it's the lesser evil here compared to having three catch clauses (for Error, RuntimeException and SomeException, respectively) with identical code. Note that I'm not trying to suppress any errors - the idea is that any exceptions thrown in the try block will continue to bubble up through the call stack as soon as I've rewinded a few things.

    Read the article

  • Exception Handling Frequency/Log Detail

    - by Cyborgx37
    I am working on a fairly complex .NET application that interacts with another application. Many single-line statements are possible culprits for throwing an Exception and there is often nothing I can do to check the state before executing them to prevent these Exceptions. The question is, based on best practices and seasoned experience, how frequently should I lace my code with try/catch blocks? I've listed three examples below, but I'm open to any advice. I'm really hoping to get some pros/cons of various approaches. I can certainly come up with some of my own (greater log granularity for the O-C approach, better performance for the Monolithic approach), so I'm looking for experience over opinion. EDIT: I should add that this application is a batch program. The only "recovery" necessary in most cases is to log the error, clean up gracefully, and quit. So this could be seen to be as much a question of log granularity as exception handling. In my mind's eye I can imagine good reasons for both, so I'm looking for some general advice to help me find an appropriate balance. Monolitich Approach class Program{ public static void Main(){ try{ Step1(); Step2(); Step3(); } catch (Exception e) { Log(e); } finally { CleanUp(); } } public static void Step1(){ ExternalApp.Dangerous1(); ExternalApp.Dangerous2(); } public static void Step2(){ ExternalApp.Dangerous3(); ExternalApp.Dangerous4(); } public static void Step3(){ ExternalApp.Dangerous5(); ExternalApp.Dangerous6(); } } Delegated Approach class Program{ public static void Main(){ try{ Step1(); Step2(); Step3(); } finally { CleanUp(); } } public static void Step1(){ try{ ExternalApp.Dangerous1(); ExternalApp.Dangerous2(); } catch (Exception e) { Log(e); throw; } } public static void Step2(){ try{ ExternalApp.Dangerous3(); ExternalApp.Dangerous4(); } catch (Exception e) { Log(e); throw; } } public static void Step3(){ try{ ExternalApp.Dangerous5(); ExternalApp.Dangerous6(); } catch (Exception e) { Log(e); throw; } } } Obsessive-Compulsive Approach class Program{ public static void Main(){ try{ Step1(); Step2(); Step3(); } finally { CleanUp(); } } public static void Step1(){ try{ ExternalApp.Dangerous1(); } catch (Exception e) { Log(e); throw; } try{ ExternalApp.Dangerous2(); } catch (Exception e) { Log(e); throw; } } public static void Step2(){ try{ ExternalApp.Dangerous3(); } catch (Exception e) { Log(e); throw; } try{ ExternalApp.Dangerous4(); } catch (Exception e) { Log(e); throw; } } public static void Step3(){ try{ ExternalApp.Dangerous5(); } catch (Exception e) { Log(e); throw; } try{ ExternalApp.Dangerous6(); } catch (Exception e) { Log(e); throw; } } } Other approaches welcomed and encouraged. Above are examples only.

    Read the article

  • Catches communication exception instead of custom fault exception - WCF

    - by Ismail S
    On Server I'm throwing the exception like this. catch(SqlException exception) { if (exception.Message.Contains("Custom error from stored proc")) { //Exception to be thrown when authentication fails. throw new FaultException<MyServiceFault>(new MyServiceFault { MessageText = exception.Message }); } } And on client end I'm catching the exception catch(FaultException<MyServiceFault> faultException) { } Here is my MyServiceFault [DataContract] public class MyServiceFault { [DataMember] public string MessageText { get; set; } [DataMember] public Guid Id { get; set; } } The problem is that on client, it doesn't go to MyServiceFault catch block instead it goes to communication exception catch block and throws this error System.ServiceModel.CommunicationException: The underlying connection was closed: The connection was closed unexpectedly. ---> System.Net.WebException I've also decorated my service method [FaultContract(typeof(MyServiceFault))] in the interface which is implemented by my service. In my web.config servicebehaviour tag consist <serviceDebug includeExceptionDetailInFaults="true" /> Any idea where I'm going wrong

    Read the article

  • Exception handling policy in libraries

    - by Asaf R
    When building a .NET library, what's your exception handling policy? In specific, what's your policy about handling exceptions inside library calls and exposing them to calling code? Would you treat a library function as any other, thus letting all exceptions it can't handle flow out of it as-is? Would you create a custom exception for that library? Would you catch all exceptions and throw the library's exception instead? Would you set the original exception as the library's exception internal exception? How would the library dependence on a DB affect your exception-handling policy? What other guidelines and rules would you suggest?

    Read the article

  • Central Exception Handler

    - by J-unior
    Recently I've been thinking about a general ExceptionHandler, that I could initialize once in my app context and inject it everywhere. The idea that it will have quite simple interface with just public void handle(Exception ex), and then according to exception type it should decide what to do, maybe just log it, or show an alert message to the user, or maybe kill the whole app. The question is, what is the prettiest way to write such handler without lots of instanceofs? Unfortunately googling gives me only the default exception handler for RuntimeException that was introduced in Java 5. My first idea is to create an enum, that will have Class field for exception type and it will return the appropriate execution point, for example a concrete exception handler that also implements the interface public void handle(Exception ex), but with the required casting already.

    Read the article

  • Exception handling within an Exception in C#

    - by Shrewd Demon
    hi, i know this could be a little weird but a doubt is a doubt afterall... what would happen in the following situation... private void SendMail() { try { //i try to send a mail and it throws an exception } catch(Exception ex) { //so i will handle that exception over here //and since an exception occurred while sending a mail //i will log an event with the eventlog //All i want to know is what if an exception occurs here //while writing the error log, how should i handle it?? } } Thank you.

    Read the article

  • What happens if my IExceptionPublisher throws an Exception?

    - by Graphain
    Hi, I'm using the .NET Exception Management Application Block (EMAB). As part of this I am implementing IExceptionPublisher classes. However, I am wondering what happens if these publishers encounter an Exception. I had a bit of a look around and apparently they are meant to do something like this: try { /* Normal Exception Publishing */ } catch { ExceptionManager.PublishInternalException(exception, additionalInfo); } Source: One caveat: what happens if there is an exception in our custom publisher code, preventing the publishing to MSMQ? For that, we turn to the ExceptionManager.PublishInternalException method, which will publish the exception to the default publisher, which is the Windows application event log. However, PublishInternalException is both protected and internal so I would have to be implementing ExceptionManager, not IExceptionPublisher, to access it.

    Read the article

  • Globally Log Catch Exception e

    - by sqlBugs
    Suppose that I have a legacy java application with thousands of lines of code which do: try { // stuff } catch (Exception e) { // eat the exception } Is there any global option that I could flip or 3rd party JAR which would log all "eaten" exceptions? I know that I could do a massive find replace (search for catch (Exception e) { and replace it with catch(Exception e) { logException(e);) but I was wondering if there was a better solution. Thanks!

    Read the article

  • Exception.Data population bug?

    - by Christopher
    Okay, .NET geniuses, here's the relevant part of my code: adapter.Fill(table); return; } catch(Exception ex) { SqlException sqlEx = ex as SqlException; I have an exception that's being thrown by adapter.Fill(), and when I put a breakpoint on the first line in the exception handler, the Exception.Data property already contains a key that is unique to my application. The thing is that it does not happen every time, but only when this exception is thrown within ~2 seconds of it last being thrown. Explain that!! :) Thanks!

    Read the article

  • Multiple Exception Handlers for one exception type

    - by danish
    I am using Enterprose Library 4.1. I have created a custom exception handler called CustomHandler. This is how the configuration section would look like: <exceptionHandling> <exceptionPolicies> <add name="Exception Policy"> <exceptionTypes> <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" postHandlingAction="NotifyRethrow" name="Exception"> <exceptionHandlers> <add type="WindowsFormsApplication1.CustomHandler, WindowsFormsApplication1" name="Custom Handler" /> <add exceptionMessage="Some test mesage." exceptionMessageResourceName="" exceptionMessageResourceType="" replaceExceptionType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionHandlingException, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling" name="Replace Handler" /> </exceptionHandlers> </add> </exceptionTypes> </add> </exceptionPolicies> </exceptionHandling> There are two handlers for same exception type. What I want is that based on a certain condition one of the handlers should handle the exception. Any ideas how that can be done? Is there a way to call the other handler from inside the HandleException method of the custom handler based on some condition?

    Read the article

  • Capturing unhandled exceptions in .Net 2.0. Wrong event called.

    - by SoMoS
    Hello, I'm investigating a bit about how the unhandled exceptions are managed in .Net and I'm getting unexpected results that I would like to share with you to see what do you think about. The first one is pretty simple to see. I wrote this code to do the test, just a button that throws an Exception on the same thread that created the Form: Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Throw New Exception() End Sub Private Sub UnhandledException(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs) MsgBox(String.Format("Exception: {0}. Ending: {1}. AppDomain: {2}", CType(e.ExceptionObject, Exception).Message, e.IsTerminating.ToString(), AppDomain.CurrentDomain.FriendlyName)) End Sub Private Sub UnhandledThreadException(ByVal sender As Object, ByVal e As System.Threading.ThreadExceptionEventArgs) MsgBox(String.Format("Exception: {0}. AppDomain: {1}", e.Exception.Message(), AppDomain.CurrentDomain.FriendlyName)) End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledException AddHandler Application.ThreadException, AddressOf UnhandledThreadException End Sub End Class When I execute the code inside the Visual Studio the UnhandledException is called as expected but when I execute the application from Windows the UndhanledThreadException is called instead. ¿?¿?¿¿?¿? Someone has any idea of what can be happening here? Thanks in advance.

    Read the article

  • Java exception handling in non sequential tasks (pattern/good practice)

    - by Hernán Eche
    There are some task that should't be done in parallel, (for example opening a file, reading, writing, and closing, there is an order on that...) But... Some task are more like a shoping list, I mean they could have a desirable order but it's not a must..example in communication or loading independient drivers etc.. For that kind of tasks, I would like to know a java best practice or pattern for manage exceptions.. The java simple way is: getUFO { try { loadSoundDriver(); loadUsbDriver(); loadAlienDetectorDriver(); loadKeyboardDriver(); } catch (loadSoundDriverFailed) { doSomethingA; } catch (loadUsbDriverFailed) { doSomethingB; } catch (loadAlienDetectorDriverFailed) { doSomethingC; } catch (loadKeyboardDriverFailed) { doSomethingD; } } But what about having an exception in one of the actions but wanting to try with the next ones?? I've thought this approach, but don't seem to be a good use for exceptions I don't know if it works, doesn't matter, it's really awful!! getUFO { Exception ex=null; try { try{ loadSoundDriver(); }catch (Exception e) { ex=e; } try{ loadUsbDriver(); }catch (Exception e) { ex=e; } try{ loadAlienDetectorDriver(); }catch (Exception e) { ex=e; } try{ loadKeyboardDriver() }catch (Exception e) { ex=e; } close the file; if(ex!=null) { throw ex; } } catch (loadSoundDriverFailed) { doSomethingA; } catch (loadUsbDriverFailed) { doSomethingB; } catch (loadAlienDetectorDriverFailed) { doSomethingC; } catch (loadKeyboardDriverFailed) { doSomethingD; } } seems not complicated to find a better practice for doing that.. I still didn't thanks for any advice

    Read the article

  • Handle Arbitrary Exception, Print Default Exception Message

    - by inspectorG4dget
    I have a program, a part of which executes a loop. During the execution of this loop, there are exceptions. Obviously, I would like my program to run without errors, but for the sake of progress, I would like the program to execute over the entire input and not stop when an exception is thrown. The easiest way to do this would be by implementing and except block. However, when I do this, it excepts all exceptions and continues with the program and I never get to see the exception message (which I need in order to debug). Is there a way to except any arbitrary exception and be able to print out the exception message in the except block?

    Read the article

  • Avoiding first chance exception messages when the exception is safely handled

    - by CVertex
    The following bit of code catches the EOS Exception using (var reader = new BinaryReader(httpRequestBodyStream)) { try { while (true) { bodyByteList.Add(reader.ReadByte()); } } catch (EndOfStreamException) { } } So why do I still receive first-chance exceptions in my console? A first chance exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll Is there a way to hide these first chance exception messages?

    Read the article

  • Throwing a new exception while throwing an old exception

    - by FredOverflow
    If a destructor throws in C++ during stack unwinding caused by an exception, the program terminates. (That's why destructors should never throw in C++.) If a finally block is entered in Java because of an exception in the corresponding try block and that finally block throws another exception, the first exception is silently swallowed. This question crossed my mind: Could a programming language handle multiple exceptions being thrown at the same time? Would that be useful? Have you ever missed that ability? Is there a language that already supports this? Is there any experience with such an approach? Any thoughts?

    Read the article

  • Catch Exception only in release

    - by Cicik
    HI, I have one global generic exception handler(catch ex as Exception) for all unhandled exceptions from application. But in debug mode(app runs from VS) I don`t want that exceptions go to this global handler. Better for me is when VS stops app on place when exception occurs. How can I do this, or is there some better approach for this? thanks

    Read the article

  • How to Determine The Module a Particular Exception Class is Defined In

    - by doug
    Note: i edited my Q (in the title) so that it better reflects what i actually want to know. In the original title and in the text of my Q, i referred to the source of the thrown exception; what i meant, and what i should have referred to, as pointed out in one of the high-strung but otherwise helpful response below, is the module that the exception class is defined in. This is evidenced by the fact that, again, as pointed out in one of the answers below the answer to the original Q is that the exceptions were thrown from calls to cursor.execute and cursor.next, respectively--which of course, isn't the information you need to write the try/except block. For instance (the Q has nothing specifically to do with SQLite or the PySQLite module): from pysqlite2 import dbapi2 as SQ try: cursor.execute('CREATE TABLE pname (id INTEGER PRIMARY KEY, name VARCHARS(50)') except SQ.OperationalError: print("{0}, {1}".format("table already exists", "... 'CREATE' ignored")) # cursor.execute('SELECT * FROM pname') while 1: try: print(cursor.next()) except StopIteration: break # i let both snippets error out to see the exception thrown, then coded the try/finally blocks--but that didn't tell me anything about which module the exception class is defined. In my example, there's only a single imported module, but where there are many more, i am interested to know how an experienced pythonista identifies the exception source (search-the-docs-till-i-happen-to-find-it is my current method). [And yes i am aware there's a nearly identical question on SO--but for C# rather than python, plus if you read the author's edited version, you'll see he's got a different problem in mind.]

    Read the article

  • Exception handling problem in release mode

    - by lama-power
    I have application with this code: Module Startup <STAThread()> _ Public Sub Main() Try Application.EnableVisualStyles() Application.SetCompatibleTextRenderingDefault(False) InitApp() Dim login As New LoginForm() Dim main As New MainForm() Application.Run(login) If login.DialogResult = DialogResult.OK Then ActUser = login.LoggedUser main.ShowDialog() End If DisposeApp() Catch ex As Exception ErrMsg(ex, "Error!", ErrorLogger.ErrMsgType.CriticalError) End End Try End Sub End Module in debug mode everithing is OK. But in release mode when somewhere in application exception occurs my global catch in Main method doesn`t catch exception. What is the problem please?

    Read the article

  • python generic exception handling and return arg on exception

    - by rikAtee
    I am trying to create generic exception handler - for where I can set an arg to return in case of exception, inspired from this answer. import contextlib @contextlib.contextmanager def handler(default): try: yield except Exception as e: yield default def main(): with handler(0): return 1 / 0 with handler(0): return 100 / 0 with handler(0): return 'helllo + 'cheese' But this results in RuntimeError: generator didn't stop after throw()

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >