Search Results

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

Page 15/90 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • What does msvc 6 throw when an integer divide by zero occurs?

    - by EvilTeach
    I have been doing a bit of experimenting, and have discovered that an exception is being thrown, when an integer divide by zero occurs. #include <iostream> #include <stdexcept> using namespace std; int main ( void ) { try { int x = 3; int y = 0; int z = x / y; cout << "Didn't throw or signal" << endl; } catch (std::exception &e) { cout << "Caught exception " << e.what() << endl; } return 0; } Clearly it is not throwing a std::exception. What else might it be throwing?

    Read the article

  • Java implementing Exception Handling

    - by user69514
    I am trying to implement an OutOfStockException for when the user attempts to buy more items than there are available. I'm not sure if my implementation is correct. Does this look OK to you? public class OutOfStockException extends Exception { public OutOfStockException(){ super(); } public OutOfStockException(String s){ super(s); } } This is the class where I need to test it: import javax.swing.JOptionPane; public class SwimItems { static final int MAX = 100; public static void main (String [] args) { Item [] items = new Item[MAX]; int numItems; numItems = fillFreebies(items); numItems += fillTaxable(items,numItems); numItems += fillNonTaxable(items,numItems); sellStuff(items, numItems); } private static int num(String which) { int n = 0; do { try{ n=Integer.parseInt(JOptionPane.showInputDialog("Enter number of "+which+" items to add to stock:")); } catch(NumberFormatException nfe){ System.out.println("Number Format Exception in num method"); } } while (n < 1 || n > MAX/3); return n; } private static int fillFreebies(Item [] list) { int n = num("FREEBIES"); for (int i = 0; i < n; i++) try{ list [i] = new Item(JOptionPane.showInputDialog("What freebie item will you give away?"), Integer.parseInt(JOptionPane.showInputDialog("How many do you have?"))); } catch(NumberFormatException nfe){ System.out.println("Number Format Exception in fillFreebies method"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Array Index Out Of Bounds Exception in fillFreebies method"); } return n; } private static int fillTaxable(Item [] list, int number) { int n = num("Taxable Items"); for (int i = number ; i < n + number; i++) try{ list [i] = new TaxableItem(JOptionPane.showInputDialog("What taxable item will you sell?"), Double.parseDouble(JOptionPane.showInputDialog("How much will you charge (not including tax) for each?")), Integer.parseInt(JOptionPane.showInputDialog("How many do you have?"))); } catch(NumberFormatException nfe){ System.out.println("Number Format Exception in fillTaxable method"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Array Index Out Of Bounds Exception in fillTaxable method"); } return n; } private static int fillNonTaxable(Item [] list, int number) { int n = num("Non-Taxable Items"); for (int i = number ; i < n + number; i++) try{ list [i] = new SaleItem(JOptionPane.showInputDialog("What non-taxable item will you sell?"), Double.parseDouble(JOptionPane.showInputDialog("How much will you charge for each?")), Integer.parseInt(JOptionPane.showInputDialog("How many do you have?"))); } catch(NumberFormatException nfe){ System.out.println("Number Format Exception in fillNonTaxable method"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Array Index Out Of Bounds Exception in fillNonTaxable method"); } return n; } private static String listEm(Item [] all, int n, boolean numInc) { String list = "Items: "; for (int i = 0; i < n; i++) { try{ list += "\n"+ (i+1)+". "+all[i].toString() ; if (all[i] instanceof SaleItem) list += " (taxable) "; if (numInc) list += " (Number in Stock: "+all[i].getNum()+")"; } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Array Index Out Of Bounds Exception in listEm method"); } catch(NullPointerException npe){ System.out.println("Null Pointer Exception in listEm method"); } } return list; } private static void sellStuff (Item [] list, int n) { int choice; do { try{ choice = Integer.parseInt(JOptionPane.showInputDialog("Enter item of choice: "+listEm(list, n, false))); } catch(NumberFormatException nfe){ System.out.println("Number Format Exception in sellStuff method"); } }while (JOptionPane.showConfirmDialog(null, "Another customer?")==JOptionPane.YES_OPTION); JOptionPane.showMessageDialog(null, "Remaining "+listEm(list, n, true)); } }

    Read the article

  • how to debug ExceptionInInitializationError?

    - by grmn.bob
    I am getting an exception in a very simple 'study' application, so I expect the problem to be in my project setup, but I don't know how to debug ... What is the context of the exception, "ExceptionInInitializationError"? Where is it documented? A: Search Android Developers Guide Stack trace from within Eclipse Debugger with: select thread - right-click - copy stack Thread [<3> main] (Suspended (exception ExceptionInInitializerError)) Class.newInstance() line: 1479 Instrumentation.newActivity(ClassLoader, String, Intent) line: 1021 ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2367 ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2470 ActivityThread.access$2200(ActivityThread, ActivityThread$ActivityRecord, Intent) line: 119 ActivityThread$H.handleMessage(Message) line: 1821 ActivityThread$H(Handler).dispatchMessage(Message) line: 99 Looper.loop() line: 123 ActivityThread.main(String[]) line: 4310 Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method] Method.invoke(Object, Object...) line: 521 ZygoteInit$MethodAndArgsCaller.run() line: 860 ZygoteInit.main(String[]) line: 618 NativeStart.main(String[]) line: not available [native method]

    Read the article

  • Cost of exception handlers in Python

    - by Thilo
    In another question, the accepted answer suggested replacing a (very cheap) if statement in Python code with a try/except block to improve performance. Coding style issues aside, and assuming that the exception is never triggered, how much difference does it make (performance-wise) to have an exception handler, versus not having one, versus having a compare-to-zero if-statement?

    Read the article

  • Why doesn't Visual Studio show an exception message when my exception occurs in a static constructor

    - by Tim Goodman
    I'm running this C# code in Visual Studio in debug mode: public class MyHandlerFactory : IHttpHandlerFactory { private static Dictionary<string, bool> myDictionary = new Dictionary<string, bool>(); static MyHandlerFactory() { myDictionary.Add("someKey",true); myDictionary.Add("someKey",true); // fails due to duplicate key } } Outside of the static constructor, when I get to the line with the error Visual Studio highlights it and pops up a message about the exception. But in the static constructor I get no such message. I am stepping through line-by-line, so I know that I'm getting to that line and no further. Why is this? (I have no idea if that fact that my class implements IHttpHandlerFactory matters, but I included it just in case.) This is VS2005, .Net 2.0

    Read the article

  • Catch Exception in Application Startup (VS.Net)

    - by clawson
    I'm getting a System.NullReferenceException when my application starts up (after a small login screen) which doesn't crash the entire app but prevents it from loading correctly. How can I get the VS.Net debugger to stop at the error so I can fix it? The output I'm getting in the Immediate Window is: A first chance exception of type 'System.NullReferenceException' occurred in GrelisCrampApp.exe

    Read the article

  • handling java exception

    - by Noona
    This questions is related to java exception, why are there some cases that when an exception thrown the program exits even though the exception was caught and there was no exit() statement? my code looks something like this void bindProxySocket(DefaultHttpClientConnection proxyConnection, String hostName, HttpParams params) { if (!proxyConnection.isOpen()) { Socket socket = null; try { socket = new Socket(hostName, 80); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { proxyConnection.bind(socket, params); } catch(IOException e) { System.err.println ("couldn't bind socket"); e.printStackTrace(); } } } and then I call this method like this: bindProxySocket(proxyConn, hostName, params1); but, the program exits, although I want to handle the exception by doing something else, can it be because I didn't enclose the method call within a try catch clause? what happens if I catch the exception again even though it's already in the method? and what should I do if i want to clean resources only if an exception occurs and otherwise I want to continue with the program? I am guessing in this case I have to include the whole piece of code until I can clean the resources with in a try statement or can I do it in the handle exception statement? some of these questions are on this specific case, but I would like to get a thorough answer to all my questions for future reference. thanks

    Read the article

  • "Undefined Symbols" when inheriting from stdexcept classes

    - by Austin Hyde
    Here is an exception defined in <stdexcept>: class length_error : public logic_error { public: explicit length_error(const string& __arg); }; Here is my exception: class rpn_expression_error : public logic_error { public: explicit rpn_expression_error(const string& __arg); }; Why do I get this error when <stdexcept> does not? Undefined symbols: rpn_expression_error::rpn_expression_error(/*string*/ const&), referenced from: ... ld: symbol(s) not found

    Read the article

  • Why do IOExceptions occur in ReadableByteChannel.read()

    - by Steffen Heil
    Hi The specification of ReadableByteChannel.read() shows -1 as result value for end-of-stream. Moreover it specifies ClosedByInterruptExceptionas possible result if the thread is interrupted. Now I thought that would be all - and it is most of the time. However, now and then I get the following: java.io.IOException: Eine vorhandene Verbindung wurde vom Remotehost geschlossen at sun.nio.ch.SocketDispatcher.read0(Native Method) at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:25) at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:233) at sun.nio.ch.IOUtil.read(IOUtil.java:206) at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:236) at ... I do not unterstand why I don't get -1 in this case. Also this is not a clean exception, as I cannot catch it without catching any possible IOException. So here are my questions: Why is this exception thrown in the first place? Is it safe to assume that ANY exception thrown by read are about the socket being closed? Is all this the same for write()? And by the way: If I call SocketChannel.close() do I have to call SocketChannel.socket().close() as well or is this implied by the earlier? Thanks, Steffen

    Read the article

  • "Row not found or changed" Problem

    - by winston schröder
    Hi there, I'm working on a SQL CE Database and get into the "Row nor found or changed" exception. The exception only occurs when I try to update. On the first Run after the insert it shows up a MemberChangeConflict which says, that my Column Created_at has in all three values (current, original, database) the same. But in a second attempt it doesn't appear anymore. The DataContext is instanciated on Startup and freed on Exit of my Local(!) Application. I use a sqlmetal generated mapping and code file. In the map I added some Associations and set the timemstamp columns UpdateCheck property to Always while all other have the setting never. The Timestamp Column is marked as isVersion="true", the Id Column as Primary Key. Since I don't dispose the datacontext I expected to be using implicit transaction. When I run the SubmitChanges Method within a TransactionScope. Can anyone tell me how I can update the timestamp within the code ? I know about the Problems one has to deal with if you dispose the datacontext. So I decided not to do this since I use a Single User Local DB Cache File. (I did already use a version where I disposed the datacontext after every usage, but this version had a real bad performance and error rate, so I decided to choose the other variant.) LibDB.Client.Vehicles tmp = null; try { tmp = e.Parameter as LibDB.Client.Vehicles; if (tmp == null) return; if (!this._dc.Vehicles.Contains(tmp)) { this._dc.Vehicles.Attach(tmp); } this.ShowChangesReport(this._dc.GetChangeSet()); using (TransactionScope ts = new TransactionScope()) { try { this._dc.SubmitChanges(); ts.Complete(); } catch (ChangeConflictException cce) { Console.WriteLine("Optimistic concurrency error."); Console.WriteLine(cce.Message); Console.ReadLine(); foreach (ObjectChangeConflict occ in this._dc.ChangeConflicts) { MetaTable metatable = this._dc.Mapping.GetTable(occ.Object.GetType()); LibDB.Client.Vehicles entityInConflict = (LibDB.Client.Vehicles)occ.Object; Console.WriteLine("Table name: {0}", metatable.TableName); Console.Write("Vin: "); Console.WriteLine(entityInConflict.Vin); foreach (MemberChangeConflict mcc in occ.MemberConflicts) { object currVal = mcc.CurrentValue; object origVal = mcc.OriginalValue; object databaseVal = mcc.DatabaseValue; MemberInfo mi = mcc.Member; Console.WriteLine("Member: {0}", mi.Name); Console.WriteLine("current value: {0}", currVal); Console.WriteLine("original value: {0}", origVal); Console.WriteLine("database value: {0}", databaseVal); } throw cce; } } catch (Exception ex) { this.ShowChangeConflicts(this._dc.ChangeConflicts); Console.WriteLine(ex.Message); } } this.ShowChangesReport(this._dc.GetChangeSet());

    Read the article

  • Is there a reason Image.FromFile throws an OutOfMemoryException for an invalid image format?

    - by Arc
    I am writing code that catches this OutOfMemoryException and throws a new, more intuitive exception: /// ... /// <exception cref="FormatException">The file does not have a valid image format.</exception> public static Image OpenImage( string filename ) { try { return Image.FromFile( filename, ); } catch( OutOfMemoryException ex ) { throw new FormatException( "The file does not have a valid image format.", ex ); } } Is this code acceptable to its user, or is OutOfMemoryException intentionally being thrown for a particular reason?

    Read the article

  • Faster way to perform checks on method arguments

    - by AndyC
    This is mostly just out of curiosity, and is potentially a silly question. :) I have a method like this: public void MyMethod(string arg1, string arg2, int arg3, string arg4, MyClass arg5) { // some magic here } None of the arguments can be null, and none of the string arguments can equal String.Empty. Instead of me having a big list of: if(arg1 == string.Empty || arg1 == null) { throw new ArgumentException("issue with arg1"); } is there a quicker way to just check all the string arguments? Apologies if my question isn't clear. Thanks!

    Read the article

  • C#: Exception to throw when a certain type was expected

    - by cbp
    I know this sort of code is not best practice, but nevertheless in certain situations I find it is a simpler solution: if (obj.Foo is Xxxx) { // Do something } else if (obj.Foo is Yyyy) { // Do something } else { throw new Exception("Type " + obj.Foo.GetType() + " is not handled."); } Anyone know if there is a built-in exception I can throw in this case?

    Read the article

  • Getting windows error reporting dialog

    - by Michael
    In my C# app, even I handle exception : Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); and then in handler showing dialog box and doing Application.Exit still getting windows error reporting dialog with Send, Don't Dend... How to prevent windows error reporting dialog from popping up?

    Read the article

  • Powershell 2.0 error handling - Command line call vs. ISE

    - by Gromix
    Hi, In the context of deployment scripts, I would like to capture any error than happens and stop immediately. I have notice some significant differences between the following calls: powershell.exe -File Script.ps1 powershell.exe -Command "& '.\Script.ps1'" powershell.exe .\Script.ps1 For example, the -File call will handle errors in the exact same way as the ISE. The other two seem to ignore the $ErrorActionPreference variable, and do not seem to catch Write-Error in try/catch blocks. Could someone help me understand the implications of each one, and why they are behaving differently? Thanks, Romain

    Read the article

  • Preserving SCRIPT tags (and more) in CKEditor

    - by Jonathan Sampson
    Update: I'm thinking the solution to this problem is in CKEDITOR.config.protectedSource(), but my regular-expression experience is proving to be too juvenile to handle this issue. How would I go about exempting all tags that contain the 'preserved' class from being touched by CKEditor? Is it possible to create a block of code within the CKEditor that will not be touched by the editor itself, and will be maintained in its intended-state until explicitly changed by the user? I've been attempting to input javascript variables (bound in script tags) and a flash movie following, but CKEditor continues to rewrite my pasted code/markup, and in doing so breaking my code. I'm working with the following setup: <script type="text/javascript"> var editor = CKEDITOR.replace("content", { height : "500px", width : "680px", resize_maxWidth : "680px", resize_minWidth : "680px", toolbar : [ ['Source','-','Save','Preview'], ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'], ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'], ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], ['Link','Unlink','Anchor'], ['Image','Table','HorizontalRule','SpecialChar'] ] }); CKFinder.SetupCKEditor( editor, "<?php print url::base(); ?>assets/ckfinder" ); </script> UPDATE: I suppose the most ideal solution would be to preserve the contents of any tag that contains class="preserve" enabling much more than the limited exclusives.

    Read the article

  • Throwing a C++ exception from inside a Linux Signal handler

    - by SoapBox
    As a thought experiment more than anything I am trying to get a C++ exception thrown "from" a linux signal handler for SIGSEGV. (I'm aware this is not a solution to any real world SIGSEGV and should never actually be done, but I thought I would try it out after being asked about it, and now I can't get it out of my head until I figure out how to do it.) Below is the closest I have come, but instead of the signal being caught properly, terminate() is being called as if no try/catch block is available. Anyone know why? Or know a way I can actually get a C++ exception from a signal handler? The code (beware, the self modifying asm limits this to running on x86_64 if you're trying to test it): #include <iostream> #include <stdexcept> #include <signal.h> #include <stdint.h> #include <errno.h> #include <string.h> #include <sys/mman.h> using namespace std; uint64_t oldaddr = 0; void thrower() { cout << "Inside thrower" << endl; throw std::runtime_error("SIGSEGV"); } void segv_handler(int sig, siginfo_t *info, void *pctx) { ucontext_t *context = (ucontext_t *)pctx; cout << "Inside SIGSEGV handler" << endl; oldaddr = context->uc_mcontext.gregs[REG_RIP]; uint32_t pageSize = (uint32_t)sysconf(_SC_PAGESIZE); uint64_t bottomOfOldPage = (oldaddr/pageSize) * pageSize; mprotect((void*)bottomOfOldPage, pageSize*2, PROT_READ|PROT_WRITE|PROT_EXEC); // 48 B8 xx xx xx xx xx xx xx xx = mov rax, xxxx *((uint8_t*)(oldaddr+0)) = 0x48; *((uint8_t*)(oldaddr+1)) = 0xB8; *((int64_t*)(oldaddr+2)) = (int64_t)thrower; // FF E0 = jmp rax *((uint8_t*)(oldaddr+10)) = 0xFF; *((uint8_t*)(oldaddr+11)) = 0xE0; } void func() { try { *(uint32_t*)0x1234 = 123456789; } catch (...) { cout << "caught inside func" << endl; throw; } } int main() { cout << "Top of main" << endl; struct sigaction action, old_action; action.sa_sigaction = segv_handler; sigemptyset(&action.sa_mask); action.sa_flags = SA_SIGINFO | SA_RESTART | SA_NODEFER; if (sigaction(SIGSEGV, &action, &old_action)<0) cerr << "Error setting handler : " << strerror(errno) << endl; try { func(); } catch (std::exception &e) { cout << "Caught : " << e.what() << endl; } cout << "Bottom of main" << endl << endl; } The actual output: Top of main Inside SIGSEGV handler Inside thrower terminate called after throwing an instance of 'std::runtime_error' what(): SIGSEGV Aborted Expected output: Top of main Inside thrower caught inside func Caught : SIGSEGV Bottom of main

    Read the article

  • Control - C exception in Java

    - by Phil
    I need to catch that exception but I can't figure out which one it is. The IDE i'm using right now doesn't allow for a program interrupt that way. I know how to user try/catch, but I don't actually know what I'm trying to catch.. Can anyone help me with this?

    Read the article

  • Why would a error get thrown inside my try-catch?

    - by George Johnston
    I'm pushing a copy of our application over to a new dev server (IIS7) and the application is blowing up on a line inside of a try-catch block. It doesn't happen locally, it actually obey's the rules of a try-catch block, go figure. Any idea why this would be happening? Shouldn't it just be failing silently? Is there something environmental I need to enable/disable? Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Line 229: Try Line 230: Here >> : _MemoryStream.Seek(6 * StartOffset, 0) Line 232: _MemoryStream.Read(_Buffer, 0, 6) Line 233: Catch ex As IOException End Try Although it doesn't matter for answering this question, I thought I would mention that it's third party code for the Geo IP lookup.

    Read the article

  • Refactor throwing not null exception if using a method that has a dependency on a certain contructor

    - by N00b
    In the method below the second constructor accepts a ForumThread object which the IncrementViewCount() method uses. There is a dependency between the method and that particular constructor. Without extracting into a new private method the null check in IncrementViewCount() and LockForumThread() (plus other methods not shown) is there some simpler re-factoring I can do or the implementation of a better design practice for this method to guard against the use of the wrong constructor with these dependent methods? Thank you for any suggestions in advance. private readonly IThread _forumLogic; private readonly ForumThread _ft; public ThreadLogic(IThread forumLogic) : this(forumLogic, null) { } public ThreadLogic(IThread forumLogic, ForumThread ft) { _forumLogic = forumLogic; _ft = ft; } public void Create(ForumThread ft) { _forumLogic.SaveThread(ft); } public void IncrementViewCount() { if (_ft == null) throw new NoNullAllowedException("_ft ForumThread is null; this must be set in the constructor"); lock (_ft) { _ft.ViewCount = _ft.ViewCount + 1; _forumLogic.SaveThread(_ft); } } public void LockForumThread() { if (_ft == null) throw new NoNullAllowedException("_ft ForumThread is null; this must be set in the constructor"); _ft.ThreadLocked = true; _forumLogic.SaveThread(_ft); }

    Read the article

  • Try catch finally blocks.. do i still need them?

    - by Phil
    I am handling errors via my global.asax in this method: Dim CurrentException As Exception CurrentException = Server.GetLastError() Dim LogFilePath As String = Server.MapPath("~/Error/" & DateTime.Now.ToString("dd-MM-yy.HH.mm") & ".txt") Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(LogFilePath) sw.WriteLine(DateTime.Now.ToString) sw.WriteLine(CurrentException.ToString()) sw.Close() In my code I currently have no other error handling. Should I still insert try, catch, finally blocks? Thanks.

    Read the article

  • Catch a thread's exception in the caller thread in Python

    - by Mikee
    Hi Everyone, I'm very new to Python and multithreaded programming in general. Basically, I have a script that will copy files to another location. I would like this to be placed in another thread so I can output "...." to indicate that the script is still running. The problem that I am having is that if the files cannot be copied it will throw an exception. This is ok if running in the main thread; however, having the following code does not work: try: threadClass = TheThread(param1, param2, etc.) threadClass.start() ##### **Exception takes place here** except: print "Caught an exception" In the thread class itself, I tried to re-throw the exception, but it does not work. I have seen people on here ask similar questions, but they all seem to be doing something more specific than what I am trying to do (and I don't quite understand the solutions offered). I have seen people mention the usage of sys.exc_info(), however I do not know where or how to use it. All help is greatly appreciated! EDIT: The code for the thread class is below: class TheThread(threading.Thread): def __init__(self, sourceFolder, destFolder): threading.Thread.__init__(self) self.sourceFolder = sourceFolder self.destFolder = destFolder def run(self): try: shul.copytree(self.sourceFolder, self.destFolder) except: raise

    Read the article

  • How to create custom exception handler for custom controls or extension methods.

    - by Shantanu Gupta
    I am creating an extension method in C# to retrieve some value from datagridview. Here if a user gives column name that doesnot exists then i want this function to throw an exception that can be handled at the place where this function will be called. How can i achieve this. public static T Value<T>(this DataGridView dgv, int RowNo, string ColName) { if (!dgv.Columns.Contains(ColName)) throw new ArgumentException("Column Name " + ColName + " doesnot exists in DataGridView."); return (T)Convert.ChangeType(dgv.Rows[RowNo].Cells[ColName].Value, typeof(T)); }

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >