Search Results

Search found 2244 results on 90 pages for 'exceptions'.

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

  • Do you use an exception class in your Perl programs? Why or why not?

    - by daotoad
    I've got a bunch of questions about how people use exceptions in Perl. I've included some background notes on exceptions, skip this if you want, but please take a moment to read the questions and respond to them. Thanks. Background on Perl Exceptions Perl has a very basic built-in exception system that provides a spring-board for more sophisticated usage. For example die "I ate a bug.\n"; throws an exception with a string assigned to $@. You can also throw an object, instead of a string: die BadBug->new('I ate a bug.'); You can even install a signal handler to catch the SIGDIE psuedo-signal. Here's a handler that rethrows exceptions as objects if they aren't already. $SIG{__DIE__} = sub { my $e = shift; $e = ExceptionObject->new( $e ) unless blessed $e; die $e; } This pattern is used in a number of CPAN modules. but perlvar says: Due to an implementation glitch, the $SIG{DIE} hook is called even inside an eval(). Do not use this to rewrite a pending exception in $@ , or as a bizarre substitute for overriding CORE::GLOBAL::die() . This strange action at a distance may be fixed in a future release so that $SIG{DIE} is only called if your program is about to exit, as was the original intent. Any other use is deprecated. So now I wonder if objectifying exceptions in sigdie is evil. The Questions Do you use exception objects? If so, which one and why? If not, why not? If you don't use exception objects, what would entice you to use them? If you do use exception objects, what do you hate about them, and what could be better? Is objectifying exceptions in the DIE handler a bad idea? Where should I objectify my exceptions? In my eval{} wrapper? In a sigdie handler? Are there any papers, articles or other resources on exceptions in general and in Perl that you find useful or enlightening.

    Read the article

  • Why use try … finally without a catch clause?

    - by Nick Rosencrantz
    The classical way to program is with try / catch but when is it appropriate to use try without catch? In Python the following appears legal and can make sense: try: #do work finally: #do something unconditional But we didn't catch anything. Similarly one could think in Java it would be try { //for example try to get a database connection } finally { //closeConnection(connection) } It looks good and suddenly I don't have to worry about exception types etc. But if this is good practice, when is it good practice? Or reasons why this is not good practice or not legal (I didn't compile the source I'm asking about and it could be a syntax error for Java but I checked that the Python surely compiles.) A related problem I've run into is that I continue writing the function / method and at the end I must return something and I'm in a place which should not be reached and it must be a return point so even if I handle the exceptions above I'm still returning null or an empty string at some point in the code which should not be reached, often the end of the method / function. I've always managed to restructure to code so that I don't have to return null since that absolutely appears to look like less than good practice.

    Read the article

  • Good practice or service for monitoring unhandled application errors for a small organization

    - by palto
    I'm working with multiple software with varying ways of monitoring for errors. When I make software, I usually send email with the stack trace to admins(usually me). Some customer software is monitored by a team who check that a particular batch run was successfull. Other software might not have any monitoring at all(someone will call when things go wrong horribly). Sending emails is good, except when things start going wrong, my mail gets filled fast. Also I don't want to solve the same problem in code for every software. Is there some relatively cheap and low maintenance software or practice to handle this. I want it to be cheap/low maintenance because usually I work alone or in teams of 5 or smaller. For example it would be great if errors would be aggregated so I don't get 10 000 emails when something unexpected happens... For clarification: By unhandled errors I mean Exceptions that were unhandled by application code that were propagated to Tomcat or Jboss. I don't need help with how to catch those errors. I need help with what to do with them. Is there any cloud application that I could send my errors to? Or some simple server to install? Or some library that can handle errors using configuration files. I use Java if that is any help.

    Read the article

  • Catch All (handled or unhandled) Exceptions

    - by andySF
    Hi, I want to catch all exceptions raised (handled or unhandled) to log them. for unhandled i use ThreadExceptionEventHandler and UnhandledExceptionEventHandler but i want to catch and exceptions that are in try catch block with or without (Exception e). It's possible to inherit the exceptions class to create a general event?

    Read the article

  • Exceptions & Interrupts

    - by Betamoo
    When I was searching for a distinction between Exceptions and Interrupts, I found this question Interrupts and exceptions on SO... Some answers there were not suitable (at least for assembly level): "Exception are software-version of an interrupt" But there exist software interrupts!! "Interrupts are asynchronous but exceptions are synchronous" Is that right? "Interrupts occur regularly" "Interrupts are hardware implemented trap, exceptions are software implemented" Same as above! I need to find if some of these answers were right , also I would be grateful if anyone could provide a better answer... Thanks!

    Read the article

  • What to do of exceptions when implementing java.lang.Iterator

    - by Vincent Robert
    The java.lang.Iterator interface has 3 methods: hasNext, next and remove. In order to implement a read-only iterator, you have to provide an implementation for 2 of those: hasNext and next. My problem is that these methods does not declare any exceptions. So if my code inside the iteration process declares exceptions, I must enclose my iteration code inside a try/catch block. My current policy has been to rethrow the exception enclosed in a RuntimeException. But this has issues because the checked exceptions are lost and the client code no longer can catch those exceptions explicitly. How can I work around this limitation in the Iterator class? Here is a sample code for clarity: class MyIterator implements Iterator { @Override public boolean hasNext() { try { return implementation.testForNext(); } catch ( SomethingBadException e ) { throw new RuntimeException(e); } } @Override public boolean next() { try { return implementation.getNext(); } catch ( SomethingBadException e ) { throw new RuntimeException(e); } } ... }

    Read the article

  • getting detailed information about structured exceptions

    - by Martin
    My Visual C++ application is compiled with /EHA option, letting me catch structured exceptions (division by zero, access violation, etc). I then translate those exceptions to my own exception class using _set_se_translator(). My goal is to improve our logging of those types of exceptions. I can get the type of exception from the EXCEPTION_RECORD structure, and the exception address. I would like to be able to gather more information, like the source file/location where the exception is thrown, the call stack, etc. Is that possible? I do create an exception minidump on structured exceptions - is there a tool to automatically get the call stack from that?

    Read the article

  • protecting COM interfaces from exceptions

    - by rmeador
    I have several dozen objects exposed through COM interfaces, each of which with many methods, totaling a few hundred methods. These interfaces expose business objects from my app to a scripting engine. I have been given the task of protecting every single one of these methods from exceptions being thrown (to catch them and return an error using COM's Error() function, which incidentally I can find no documentation on because it's impossible to google). To my understanding, this requires that I add a try/catch around the guts of each one of these methods. The catch blocks are going to be similar or identical for each and every one of these hundreds of methods, which strongly smells of a problem (massively violates the DRY principle), but I can't think of any way to avoid changing every method. As far as I can tell, these methods are invoked directly by COM, with no intervening code that I can hook into to catch the exceptions. My current best idea is to make a macro for the catch block, but that has it's own sort of code-smell. Can anyone come up with a better approach? BTW, my app's exceptions do not derive from std::exception, so if there is some way of COM automatically handling standard exceptions, it won't help. And I sadly cannot change the existing exceptions to derive from std::exception.

    Read the article

  • Which framework exceptions should every programmer know about ?

    - by Thibault Falise
    I've recently started a new project in C#, and, as I was coding some exception throw in a function, I figured out I didn't really know which exception I should use. Here are common exceptions that are often thrown in many programs : ArgumentException ArgumentNullException InvalidOperationException Are there any framework exceptions you often use in your programs ? Which exceptions should every .net programmer know about ? When do you use custom exception ?

    Read the article

  • How to break on unhandled exceptions in Silverlight

    - by Bruno Martinez
    In console .Net applications, the debugger breaks at the point of the throw (before stack unwinding) for exceptions with no matching catch block. It seems that Silverlight runs all user code inside a try catch, so the debugger never breaks. Instead, Application.UnhandledException is raised, but after catching the exception and unwinding the stack. To break when unhandled exceptions are thrown and not catched, I have to enable first chance exception breaks, which also stops the program for handled exceptions. Is there a way to remove the Silverlight try block, so that exceptions get directly to the debugger?

    Read the article

  • .NET Framework 4 updates breaking MMC.exe and other CLR.dll Exceptions

    - by Fox
    I've seen this issue floating around the net the last few weeks and I'm facing exactly the same issue. My servers are set to auto install updates using Windows update (not clever, I know), and since about 2 months ago, I've been getting strange Exceptions. The first thing that happens is that MMC.exe just crashes randomly and sometimes on startup of the console. The exception in the Windows Application log is as follow: Faulting application name: mmc.exe, version: 6.1.7600.16385, time stamp: 0x4a5bc808 Faulting module name: mscorwks.dll, version: 2.0.50727.5448, time stamp: 0x4e153960 Secondly, on the same server, I have some custom Windows services which constantly crash with exceptions : Faulting application name: Myservice.exe, version: 1.0.0.0, time stamp: 0x4f44cb11 Faulting module name: clr.dll, version: 4.0.30319.239, time stamp: 0x4e181a6d Exception code: 0xc0000005 Fault offset: 0x000378aa The exception is not in my code. I've tested and retested it. My server has the following .NET Framework updates installed: Does anyone have any idea?

    Read the article

  • NLog Exception Details Renderer

    - by jtimperley
    Originally posted on: http://geekswithblogs.net/jtimperley/archive/2013/07/28/nlog-exception-details-renderer.aspxI recently switch from Microsoft's Enterprise Library Logging block to NLog.  In my opinion, NLog offers a simpler and much cleaner configuration section with better use of placeholders, complemented by custom variables. Despite this, I found one deficiency in my migration; I had lost the ability to simply render all details of an exception into our logs and notification emails. This is easily remedied by implementing a custom layout renderer. Start by extending 'NLog.LayoutRenderers.LayoutRenderer' and overriding the 'Append' method. using System.Text; using NLog; using NLog.Config; using NLog.LayoutRenderers;   [ThreadAgnostic] [LayoutRenderer(Name)] public class ExceptionDetailsRenderer : LayoutRenderer { public const string Name = "exceptiondetails";   protected override void Append(StringBuilder builder, LogEventInfo logEvent) { // Todo: Append details to StringBuilder } }   Now that we have a base layout renderer, we simply need to add the formatting logic to add exception details as well as inner exception details. This is done using reflection with some simple filtering for the properties that are already being rendered. I have added an additional 'Register' method, allowing the definition to be registered in code, rather than in configuration files. This complements by 'LogWrapper' class which standardizes writing log entries throughout my applications. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using NLog; using NLog.Config; using NLog.LayoutRenderers;   [ThreadAgnostic] [LayoutRenderer(Name)] public sealed class ExceptionDetailsRenderer : LayoutRenderer { public const string Name = "exceptiondetails"; private const string _Spacer = "======================================"; private List<string> _FilteredProperties;   private List<string> FilteredProperties { get { if (_FilteredProperties == null) { _FilteredProperties = new List<string> { "StackTrace", "HResult", "InnerException", "Data" }; }   return _FilteredProperties; } }   public bool LogNulls { get; set; }   protected override void Append(StringBuilder builder, LogEventInfo logEvent) { Append(builder, logEvent.Exception, false); }   private void Append(StringBuilder builder, Exception exception, bool isInnerException) { if (exception == null) { return; }   builder.AppendLine();   var type = exception.GetType(); if (isInnerException) { builder.Append("Inner "); }   builder.AppendLine("Exception Details:") .AppendLine(_Spacer) .Append("Exception Type: ") .AppendLine(type.ToString());   var bindingFlags = BindingFlags.Instance | BindingFlags.Public; var properties = type.GetProperties(bindingFlags); foreach (var property in properties) { var propertyName = property.Name; var isFiltered = FilteredProperties.Any(filter => String.Equals(propertyName, filter, StringComparison.InvariantCultureIgnoreCase)); if (isFiltered) { continue; }   var propertyValue = property.GetValue(exception, bindingFlags, null, null, null); if (propertyValue == null && !LogNulls) { continue; }   var valueText = propertyValue != null ? propertyValue.ToString() : "NULL"; builder.Append(propertyName) .Append(": ") .AppendLine(valueText); }   AppendStackTrace(builder, exception.StackTrace, isInnerException); Append(builder, exception.InnerException, true); }   private void AppendStackTrace(StringBuilder builder, string stackTrace, bool isInnerException) { if (String.IsNullOrEmpty(stackTrace)) { return; }   builder.AppendLine();   if (isInnerException) { builder.Append("Inner "); }   builder.AppendLine("Exception StackTrace:") .AppendLine(_Spacer) .AppendLine(stackTrace); }   public static void Register() { Type definitionType; var layoutRenderers = ConfigurationItemFactory.Default.LayoutRenderers; if (layoutRenderers.TryGetDefinition(Name, out definitionType)) { return; }   layoutRenderers.RegisterDefinition(Name, typeof(ExceptionDetailsRenderer)); LogManager.ReconfigExistingLoggers(); } } For brevity I have removed the Trace, Debug, Warn, and Fatal methods. They are modelled after the Info methods. As mentioned above, note how the log wrapper automatically registers our custom layout renderer reducing the amount of application configuration required. using System; using NLog;   public static class LogWrapper { static LogWrapper() { ExceptionDetailsRenderer.Register(); }   #region Log Methods   public static void Info(object toLog) { Log(toLog, LogLevel.Info); }   public static void Info(string messageFormat, params object[] parameters) { Log(messageFormat, parameters, LogLevel.Info); }   public static void Error(object toLog) { Log(toLog, LogLevel.Error); }   public static void Error(string message, Exception exception) { Log(message, exception, LogLevel.Error); }   private static void Log(string messageFormat, object[] parameters, LogLevel logLevel) { string message = parameters.Length == 0 ? messageFormat : string.Format(messageFormat, parameters); Log(message, (Exception)null, logLevel); }   private static void Log(object toLog, LogLevel logLevel, LogType logType = LogType.General) { if (toLog == null) { throw new ArgumentNullException("toLog"); }   if (toLog is Exception) { var exception = toLog as Exception; Log(exception.Message, exception, logLevel, logType); } else { var message = toLog.ToString(); Log(message, null, logLevel, logType); } }   private static void Log(string message, Exception exception, LogLevel logLevel, LogType logType = LogType.General) { if (exception == null && String.IsNullOrEmpty(message)) { return; }   var logger = GetLogger(logType); // Note: Using the default constructor doesn't set the current date/time var logInfo = new LogEventInfo(logLevel, logger.Name, message); logInfo.Exception = exception; logger.Log(logInfo); }   private static Logger GetLogger(LogType logType) { var loggerName = logType.ToString(); return LogManager.GetLogger(loggerName); }   #endregion   #region LogType private enum LogType { General } #endregion } The following configuration is similar to what is provided for each of my applications. The 'application' variable is all that differentiates the various applications in all of my environments, the rest has been standardized. Depending on your needs to tweak this configuration while developing and debugging, this section could easily be pushed back into code similar to the registering of our custom layout renderer.   <?xml version="1.0"?>   <configuration> <configSections> <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/> </configSections> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <variable name="application" value="Example"/> <targets> <target type="EventLog" name="EventLog" source="${application}" log="${application}" layout="${message}${onexception: ${newline}${exceptiondetails}}"/> <target type="Mail" name="Email" smtpServer="smtp.example.local" from="[email protected]" to="[email protected]" subject="(${machinename}) ${application}: ${level}" body="Machine: ${machinename}${newline}Timestamp: ${longdate}${newline}Level: ${level}${newline}Message: ${message}${onexception: ${newline}${exceptiondetails}}"/> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="EventLog" /> <logger name="*" minlevel="Error" writeTo="Email" /> </rules> </nlog> </configuration>   Now go forward, create your custom exceptions without concern for including their custom properties in your exception logs and notifications.

    Read the article

  • Error Handling without Exceptions

    - by James
    While searching SO for approaches to error handling related to business rule validation , all I encounter are examples of structured exception handling. MSDN and many other reputable development resources are very clear that exceptions are not to be used to handle routine error cases. They are only to be used for exceptional circumstances and unexpected errors that may occur from improper use by the programmer (but not the user.) In many cases, user errors such as fields that are left blank are common, and things which our program should expect, and therefore are not exceptional and not candidates for use of exceptions. QUOTE: Remember that the use of the term exception in programming has to do with the thinking that an exception should represent an exceptional condition. Exceptional conditions, by their very nature, do not normally occur; so your code should not throw exceptions as part of its everyday operations. Do not throw exceptions to signal commonly occurring events. Consider using alternate methods to communicate to a caller the occurrence of those events and leave the exception throwing for when something truly out of the ordinary happens. For example, proper use: private void DoSomething(string requiredParameter) { if (requiredParameter == null) throw new ArgumentExpcetion("requiredParameter cannot be null"); // Remainder of method body... } Improper use: // Renames item to a name supplied by the user. Name must begin with an "F". public void RenameItem(string newName) { // Items must have names that begin with "F" if (!newName.StartsWith("F")) throw new RenameException("New name must begin with /"F/""); // Remainder of method body... } In the above case, according to best practices, it would have been better to pass the error up to the UI without involving/requiring .NET's exception handling mechanisms. Using the same example above, suppose one were to need to enforce a set of naming rules against items. What approach would be best? Having the method return a enumerated result? RenameResult.Success, RenameResult.TooShort, RenameResult.TooLong, RenameResult.InvalidCharacters, etc. Using an event in a controller class to report to the UI class? The UI calls the controller's RenameItem method, and then handles an AfterRename event that the controller raises and that has rename status as part of the event args? The controlling class directly references and calls a method from the UI class that handles the error, e.g. ReportError(string text). Something else... ? Essentially, I want to know how to perform complex validation in classes that may not be the Form class itself, and pass the errors back to the Form class for display -- but I do not want to involve exception handling where it should not be used (even though it seems much easier!) Based on responses to the question, I feel that I'll have to state the problem in terms that are more concrete: UI = User Interface, BLL = Business Logic Layer (in this case, just a different class) User enters value within UI. UI reports value to BLL. BLL performs routine validation of the value. BLL discovers rule violation. BLL returns rule violation to UI. UI recieves return from BLL and reports error to user. Since it is routine for a user to enter invalid values, exceptions should not be used. What is the right way to do this without exceptions?

    Read the article

  • User Defined Exceptions with JMX

    - by Daniel
    I have exposed methods for remote management in my application server using JMX by creating an MXBean interface, and a class to implement it. Included in this interface are operations for setting attributes on my server, and for getting the current value of attributes. For example, take the following methods: public interface WordManagerMXBean { public void addWord(String word); public WordsObject getWords(); public void removeWord(String word); } The WordsObject is a custom, serializable class used to retrieve data about the state of the server. Then I also have a WordManager class that implements the above interface. I then create a JMX agent to manage my resource: MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName wordManagerName = new ObjectName("com.example:type=WordManager"); mbs.registerMBean(wordManager, wordManagerName); I have created a client that invokes these methods, and this works as expected. However, I would like to extend this current configuration by adding user defined exceptions that can be sent back to my client. So I would like to change my interface to something like this: public interface WordManagerMXBean { public void addWord(String word) throws WordAlreadyExistsException; public WordsObject getWords(); public void removeWord(String word); } My WordAlreadyExistsException looks like this: public class WordAlreadyExistsException extends Exception implements Serializable { private static final long serialVersionUID = -9095552123119275304L; public WordAlreadyExistsException() { super(); } } When I call the addWord() method in my client, I would like to get back a WordAlreadyExistsException if the word already exists. However, when I do this, I get an error like this: java.rmi.UnmarshalException: Error unmarshaling return; nested exception is: java.lang.ClassNotFoundException: com.example.WordAlreadyExistsException The WordAlreadyExistsException, the WordsObject and the WordManagerMXBean interface are all in a single jar file that is available to both the client and the server. If I call the getWords() method, the client has no difficulty handling the WordsObject. However, if a user defined exception, like the one above, is thrown, then the client gives the error shown above. Is it possible to configure JMX to handle this exception correctly in the client? Following some searching, I noticed that there is an MBeanException class that is used to wrap exceptions. I'm not sure if this wrapping is performed by the agent automatically, or if I'm supposed to do the wrapping myself. I tried both, but in either case I get the same error on the client. I have also tried this with both checked and unchecked exceptions, again the same error occurs. One solution to this is to simply pass back the error string inside a generic error, as all of the standard java exceptions work. But I'd prefer to get back the actual exception for processing by the client. Is it possible to handle user defined exceptions in JMX? If so, any ideas how?

    Read the article

  • SwingWorker exceptions lost even when using wrapper classes

    - by Ti Strga
    I've been struggling with the usability problem of SwingWorker eating any exceptions thrown in the background task, for example, described on this SO thread. That thread gives a nice description of the problem, but doesn't discuss recovering the original exception. The applet I've been handed needs to propagate the exception upwards. But I haven't been able to even catch it. I'm using the SimpleSwingWorker wrapper class from this blog entry specifically to try and address this issue. It's a fairly small class but I'll repost it at the end here just for reference. The calling code looks broadly like try { // lots of code here to prepare data, finishing with SpecialDataHelper helper = new SpecialDataHelper(...stuff...); helper.execute(); } catch (Throwable e) { // used "Throwable" here in desperation to try and get // anything at all to match, including unchecked exceptions // // no luck, this code is never ever used :-( } The wrappers: class SpecialDataHelper extends SimpleSwingWorker { public SpecialDataHelper (SpecialData sd) { this.stuff = etc etc etc; } public Void doInBackground() throws Exception { OurCodeThatThrowsACheckedException(this.stuff); return null; } protected void done() { // called only when successful // never reached if there's an error } } The feature of SimpleSwingWorker is that the actual SwingWorker's done()/get() methods are automatically called. This, in theory, rethrows any exceptions that happened in the background. In practice, nothing is ever caught, and I don't even know why. The SimpleSwingWorker class, for reference, and with nothing elided for brevity: import java.util.concurrent.ExecutionException; import javax.swing.SwingWorker; /** * A drop-in replacement for SwingWorker<Void,Void> but will not silently * swallow exceptions during background execution. * * Taken from http://jonathangiles.net/blog/?p=341 with thanks. */ public abstract class SimpleSwingWorker { private final SwingWorker<Void,Void> worker = new SwingWorker<Void,Void>() { @Override protected Void doInBackground() throws Exception { SimpleSwingWorker.this.doInBackground(); return null; } @Override protected void done() { // Exceptions are lost unless get() is called on the // originating thread. We do so here. try { get(); } catch (final InterruptedException ex) { throw new RuntimeException(ex); } catch (final ExecutionException ex) { throw new RuntimeException(ex.getCause()); } SimpleSwingWorker.this.done(); } }; public SimpleSwingWorker() {} protected abstract Void doInBackground() throws Exception; protected abstract void done(); public void execute() { worker.execute(); } }

    Read the article

  • Exceptions over remote methods

    - by Andrei Vajna II
    What are the best practices for exceptions over remote methods? I'm sure that you need to handle all exceptions at the level of a remote method implementation, because you need to log it on the server side. But what should you do afterwards? Should you wrap the exception in a RemoteException (java) and throw it to the client? This would mean that the client would have to import all exceptions that could be thrown. Would it be better to throw a new custom exception with fewer details? Because the client won't need to know all the details of what went wrong. What should you log on the client? I've even heard of using return codes(for efficiency maybe?) to tell the caller about what happened. The important thing to keep in mind, is that the client must be informed of what went wrong. A generic answer of "Something failed" or no notification at all is unacceptable. And what about runtime (unchecked) exceptions?

    Read the article

  • Force exceptions language in English

    - by serhio
    My Visual Studio 2005 is a French one, installed on a French OS. All the exceptions I receive during debug or runtime I obtain also in French. Can I however do something that the exceptions messages be in English? For goggling, discussing etc. I tried the following: Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); throw new NullReferenceException(); obtained Object reference not set to an instance of an object. This is, surely, cool... but, as I work on a French project, I will not hardcode forcing Thread.CurrentUICulture to English. I want the English change to be only on my local machine, and don't change the project properties. Is it possible to set the exceptions language without modifying the code of the application? In VS 2008, set the Tools - Options - Environment - International Settings - Language to "English" wnd throwing the same exception obtain the ex message en French, however:

    Read the article

  • Unhandled exceptions in BackgroundWorker

    - by edg
    My WinForms app uses a number of BackgroundWorker objects to retrieve information from a database. I'm using BackgroundWorker because it allows the UI to remain unblocked during long-running database queries and it simplifies the threading model for me. I'm getting occasional DatabaseExceptions in some of these background threads, and I have witnessed at least one of these exceptions in a worker thread while debugging. I'm fairly confident these exceptions are timeouts which I suppose its reasonable to expect from time to time. My question is about what happens when an unhandled exception occurs in one of these background worker threads. I don't think I can catch an exception in another thread, but can I expect my WorkerCompleted method to be executed? Is there any property or method of the BackgroundWorker I can interrogate for exceptions?

    Read the article

  • Should I catch exceptions thrown when closing java.sql.Connection

    - by jb
    Connection.close() may throw SqlException, but I have always assumed that it is safe to ignore any such exceptions (and I have never seen code that does not ignore them). Normally I would write: try{ connection.close(); }catch(Exception e) {} Or try{ connection.close(); }catch(Exception e) { logger.log(e.getMessage(), e); } The question is: Is it bad practice (and has anyone had problems when ignoring such exeptions). When Connection.close() does throw any exception. If it is bad how should I handle the exception. Comment: I know that discarding exceptions is evil, but I'm reffering only to exceptions thrown when closing a connection (and as I've seen this is fairly common in this case). Does anyone know when Connection.close() may throw anything?

    Read the article

  • Handling exceptions, is this a good way?

    - by Jorge Córdoba
    We're struggling with a policy to correctly handle exceptions in our application. Here's our goals for it (summarized): Handle only specific exceptions. Handle only exceptions that you can correct Log only once. We've come out with a solution that involves a generic Application Specific Exception and works like this in a piece of code: try { // Do whatever } catch(ArgumentNullException ane) { // Handle, optinally log and continue } catch(AppSpecificException) { // Rethrow, don't log, don't do anything else throw; } catch(Exception e) { // Log, encapsulate (so that it won't be logged again) and throw Logger.Log("Really bad thing", e.Message, e); throw new AppSpecificException(e) } All exception is logged and then turned to an AppSpecificException so that it won't be logged again. Eventually it will reach the last resort event handler that will deal with it if it has to. I don't have so much experience with exception handling patterns... Is this a good way to solve our goals? Has it any major drawbacks or big red warnings?

    Read the article

  • how to handle exceptions/errors in php?

    - by fayer
    when using 3rd part libraries they tend to throw exceptions to the browser and hence kill the script. eg. if im using doctrine and insert a duplicate record to the database it will throw an exception. i wonder, what is best practice for handling these exceptions. should i always do a try...catch? but doesn't that mean that i will have try...catch all over the script and for every single function/class i use? Or is it just for debugging? i don't quite get the picture. Cause if a record already exists in a database, i want to tell the user "Record already exists". And if i code a library or a function, should i always use "throw new Expcetion($message, $code)" when i want to create an error? Please shed a light on how one should create/handle exceptions/errors. Thanks

    Read the article

  • Catching uncaught exceptions

    - by kajyr
    Hi everybody. In my workplace we are mantaining a lot of ecommerce websites, some coded better than others. On some of those, sometimes uncaught exceptions are thrown, and showed by the alertbox from the flash player debug (If you have it installed). To rise the average user experience I'd like to report all those exceptions throught a in house tool we already have. Is there a way to catch those exceptions? Maybe the flash player debug exposes them to javascript, or in some other way.

    Read the article

  • What are developer's problems with helpful error messages?

    - by Moo-Juice
    It continue to astounds me that, in this day and age, products that have years of use under their belt, built by teams of professionals, still to this day - fail to provide helpful error messages to the user. In some cases, the addition of just a little piece of extra information could save a user hours of trouble. A program that generates an error, generated it for a reason. It has everything at its disposal to inform the user as much as it can, why something failed. And yet it seems that providing information to aid the user is a low-priority. I think this is a huge failing. One example is from SQL Server. When you try and restore a database that is in use, it quite rightly won't let you. SQL Server knows what processes and applications are accessing it. Why can't it include information about the process(es) that are using the database? I know not everyone passes an Applicatio_Name attribute on their connection string, but even a hint about the machine in question could be helpful. Another candidate, also SQL Server (and mySQL) is the lovely string or binary data would be truncated error message and equivalents. A lot of the time, a simple perusal of the SQL statement that was generated and the table shows which column is the culprit. This isn't always the case, and if the database engine picked up on the error, why can't it save us that time and just tells us which damned column it was? On this example, you could argue that there may be a performance hit to checking it and that this would impede the writer. Fine, I'll buy that. How about, once the database engine knows there is an error, it does a quick comparison after-the-fact, between values that were going to be stored, versus the column lengths. Then display that to the user. ASP.NET's horrid Table Adapters are also guilty. Queries can be executed and one can be given an error message saying that a constraint somewhere is being violated. Thanks for that. Time to compare my data model against the database, because the developers are too lazy to provide even a row number, or example data. (For the record, I'd never use this data-access method by choice, it's just a project I have inherited!). Whenever I throw an exception from my C# or C++ code, I provide everything I have at hand to the user. The decision has been made to throw it, so the more information I can give, the better. Why did my function throw an exception? What was passed in, and what was expected? It takes me just a little longer to put something meaningful in the body of an exception message. Hell, it does nothing but help me whilst I develop, because I know my code throws things that are meaningful. One could argue that complicated exception messages should not be displayed to the user. Whilst I disagree with that, it is an argument that can easily be appeased by having a different level of verbosity depending on your build. Even then, the users of ASP.NET and SQL Server are not your typical users, and would prefer something full of verbosity and yummy information because they can track down their problems faster. Why to developers think it is okay, in this day and age, to provide the bare minimum amount of information when an error occurs? It's 2011 guys, come on.

    Read the article

  • Python Forgiveness vs. Permission and Duck Typing

    - by darkfeline
    In Python, I often hear that it is better to "beg forgiveness" (exception catching) instead of "ask permission" (type/condition checking). In regards to enforcing duck typing in Python, is this try: x = foo.bar except AttributeError: pass else: do(x) better or worse than if hasattr(foo, "bar"): do(foo.bar) else: pass in terms of performance, readability, "pythonic", or some other important factor?

    Read the article

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