Search Results

Search found 4116 results on 165 pages for 'baron throw'.

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

  • Is it ok to throw NotImplemented exception in virtual methods?

    - by Axarydax
    I have a base class for some plugin-style stuff, and there are some methods that are absolutely required to be implemented. I currently declare those in the base class as virtual, for example public virtual void Save { throw new NotImplementedException(); } and in the descendand I have a public override void Save() { //do stuff } Is it a good practice to throw a NotImplementedException there? The descendand classes could for example be the modules for handling different file formats. Thanks

    Read the article

  • Is it standard behavior for this code to throw a NullPointerException?

    - by Eric
    I've had a big problem in some library code, which I've pinned down to a single statement: System.out.println((String) null); Ok, the code doesn't actually look like that, but it certainly calls println with a null argument. Doing this causes my whole applicaio to throw an unexpected NullPointerException. In general, should println throw this exception under that circumstance, or is this non-standard behavior due to a poor implementation of the out instance?

    Read the article

  • Would I want to throw an exception or an error in this PHP script?

    - by Tower
    Hi, I have a PHP script that runs database queries. Now, if a query fails, should I trigger an error or throw an exception? I noticed that if I do the latter, the script execution will stop after facing the exception. My code is as follows: if (!$this->connection[0]->query($this->query)) throw new Exception($this->connection[0]->error); What are the pros and cons of using exceptions for this kind of cases (failed queries)?

    Read the article

  • MS Exam 70-536 - How to throw and handle exception from thread?

    - by Max Gontar
    Hello! In MS Exam 70-536 .Net Foundation, Chapter 7 "Threading" in Lesson 1 Creating Threads there is a text: Be aware that because the WorkWithParameter method takes an object, Thread.Start could be called with any object instead of the string it expects. Being careful in choosing your starting method for a thread to deal with unknown types is crucial to good threading code. Instead of blindly casting the method parameter into our string, it is a better practice to test the type of the object, as shown in the following example: ' VB Dim info As String = o as String If info Is Nothing Then Throw InvalidProgramException("Parameter for thread must be a string") End If // C# string info = o as string; if (info == null) { throw InvalidProgramException("Parameter for thread must be a string"); } So, I've tried this but exception is not handled properly (no console exception entry, program is terminated), what is wrong with my code (below)? class Program { static void Main(string[] args) { Thread thread = new Thread(SomeWork); try { thread.Start(null); thread.Join(); } catch (InvalidProgramException ex) { Console.WriteLine(ex.Message); } finally { Console.ReadKey(); } } private static void SomeWork(Object o) { String value = (String)o; if (value == null) { throw new InvalidProgramException("Parameter for "+ "thread must be a string"); } } } Thanks for your time!

    Read the article

  • Can this line of code really throw an IndexOutOfRange exception?

    - by Jonathan M
    I am getting an IndexOutOfRange exception on the following line of code: var searchLastCriteria = (SearchCriteria)Session.GetSafely(WebConstants.KeyNames.SEARCH_LAST_CRITERIA); I'll explain the above here: SearchCriteria is an Enum with only two values Session is the HttpSessionState GetSafely is an extension method that looks like this: public static object GetSafely(this HttpSessionState source, string key) { try { return source[key]; } catch (Exception exc) { log.Info(exc); return null; } } WebConstants.KeyNames.SEARCH_LAST_CRITERIA is simply a constant I've tried everything to replicate this error, but I cannot reproduce it. I am beginning to think the stack trace is wrong. I thought perhaps the exception was actually coming from the GetSafely call, but it is swallowing the exceptions, so that can't be the case, and even if it was, it should show up in the stack trace. Is there anything in the line of code above that could possible throw an IndexOutOfRange exception? I know the line will throw an NullReferenceException if GetSafely returns null, and it will also throw an InvalidCastException if it returns anything that cannot be cast to SearchCriteria, but an IndexOutOfRange exception? I'm scratching my head here. Here is the stack trace: $LOG--> 2010-06-11 07:01:33,814 [ERROR] SERVERA (14) Web.Global - Index was outside the bounds of the array. System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array. at IterateSearchResult(Boolean next) in C:\Projects\Web\UserControls\AccountHeader.ascx.cs:line 242 at nextAccountLink_Click(Object sender, EventArgs e) in C:\Projects\Web\UserControls\AccountHeader.ascx.cs:line 232

    Read the article

  • What to throw in a C++ class wrapping a C library ?

    - by ereOn
    I have to create a set of wrapping C++ classes around an existing C library. For many objects of the C library, the construction is done by calling something like britney_spears* create_britney_spears() and the opposite function void free_britney_spears(britney_spears* brit). If the allocation of a britney_spears fails, create_britney_spears() returns NULL. This is, as far as I know, a very common pattern. Now I want to wrap this inside a C++ class. //britney_spears.hpp class BritneySpears { public: BritneySpears(); private: boost::shared_ptr<britney_spears> m_britney_spears; }; And here is the implementation: // britney_spears.cpp BritneySpears::BritneySpears() : m_britney_spears(create_britney_spears(), free_britney_spears) { if (!m_britney_spears) { // Here I should throw something to abort the construction, but what ??! } } So the question is in the code sample: What should I throw to abort the constructor ? I know I can throw almost anything, but I want to know what is usually done. I have no other information about why the allocation failed. Should I create my own exception class ? Is there a std exception for such cases ? Many thanks.

    Read the article

  • Examples of bad variable names and reasons [on hold]

    - by user470184
    I'll start with a class in the jdk package : public final class Sdp { should be : public final class SocketsDirectProtocol { Sdp is class name, this is ambigious, should be : Class<?> cl = Class.forName("java.net.SdpSocketImpl", true, null); should be : Class<?> clazz = Class.forName("java.net.SdpSocketImpl", true, null); cl is ambiguous private static void setAccessible(final AccessibleObject o) { should be : private static void setAccessible(final AccessibleObject accessibleObject) { There are various other examples in this class, do you have similar and/or differing examples of variables that were named badly ? package com.oracle.net; public final class Sdp { private Sdp() { } /** * The package-privage ServerSocket(SocketImpl) constructor */ private static final Constructor<ServerSocket> serverSocketCtor; static { try { serverSocketCtor = (Constructor<ServerSocket>) ServerSocket.class.getDeclaredConstructor(SocketImpl.class); setAccessible(serverSocketCtor); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } /** * The package-private SdpSocketImpl() constructor */ private static final Constructor<SocketImpl> socketImplCtor; static { try { Class<?> cl = Class.forName("java.net.SdpSocketImpl", true, null); socketImplCtor = (Constructor<SocketImpl>)cl.getDeclaredConstructor(); setAccessible(socketImplCtor); } catch (ClassNotFoundException e) { throw new AssertionError(e); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } private static void setAccessible(final AccessibleObject o) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { o.setAccessible(true); return null; } }); } /** * SDP enabled Socket. */ private static class SdpSocket extends Socket { SdpSocket(SocketImpl impl) throws SocketException { super(impl); } } /** * Creates a SDP enabled SocketImpl */ private static SocketImpl createSocketImpl() { try { return socketImplCtor.newInstance(); } catch (InstantiationException x) { throw new AssertionError(x); } catch (IllegalAccessException x) { throw new AssertionError(x); } catch (InvocationTargetException x) { throw new AssertionError(x); } } /** * Creates an unconnected and unbound SDP socket. The {@code Socket} is * associated with a {@link java.net.SocketImpl} of the system-default type. * * @return a new Socket * * @throws UnsupportedOperationException * If SDP is not supported * @throws IOException * If an I/O error occurs */ public static Socket openSocket() throws IOException { SocketImpl impl = createSocketImpl(); return new SdpSocket(impl); } /** * Creates an unbound SDP server socket. The {@code ServerSocket} is * associated with a {@link java.net.SocketImpl} of the system-default type. * * @return a new ServerSocket * * @throws UnsupportedOperationException * If SDP is not supported * @throws IOException * If an I/O error occurs */ public static ServerSocket openServerSocket() throws IOException { // create ServerSocket via package-private constructor SocketImpl impl = createSocketImpl(); try { return serverSocketCtor.newInstance(impl); } catch (IllegalAccessException x) { throw new AssertionError(x); } catch (InstantiationException x) { throw new AssertionError(x); } catch (InvocationTargetException x) { Throwable cause = x.getCause(); if (cause instanceof IOException) throw (IOException)cause; if (cause instanceof RuntimeException) throw (RuntimeException)cause; throw new RuntimeException(x); } } /** * Opens a socket channel to a SDP socket. * * <p> The channel will be associated with the system-wide default * {@link java.nio.channels.spi.SelectorProvider SelectorProvider}. * * @return a new SocketChannel * * @throws UnsupportedOperationException * If SDP is not supported or not supported by the default selector * provider * @throws IOException * If an I/O error occurs. */ public static SocketChannel openSocketChannel() throws IOException { FileDescriptor fd = SdpSupport.createSocket(); return sun.nio.ch.Secrets.newSocketChannel(fd); } /** * Opens a socket channel to a SDP socket. * * <p> The channel will be associated with the system-wide default * {@link java.nio.channels.spi.SelectorProvider SelectorProvider}. * * @return a new ServerSocketChannel * * @throws UnsupportedOperationException * If SDP is not supported or not supported by the default selector * provider * @throws IOException * If an I/O error occurs */ public static ServerSocketChannel openServerSocketChannel() throws IOException { FileDescriptor fd = SdpSupport.createSocket(); return sun.nio.ch.Secrets.newServerSocketChannel(fd); } }

    Read the article

  • How do I handle all the exceptions in a C# class where both ctor and finalizer throw exceptions?

    - by Frank
    How can I handle all exceptions for a class similar to the following under certain circumstances? class Test : IDisposable { public Test() { throw new Exception("Exception in ctor"); } public void Dispose() { throw new Exception("Exception in Dispose()"); } ~Test() { this.Dispose(); } } I tried this but it doesn't work: static void Main() { Test t = null; try { t = new Test(); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } // t is still null } I have also tried to use "using" but it does not handle the exception thrown from ~Test(); static void Main() { try { using (Test t = new Test()) { } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } Any ideas how can I work around?

    Read the article

  • XmlSerializer.Serialize doesn't save a file and doesn't throw an exception.

    - by Wodzu
    Hi guys. I am having problem with saving of my object. Take a look at this code: public void SerializeToXML(String FileName) { XmlSerializer fSerializer = new XmlSerializer(typeof(Configuration)); using (Stream fStream = new FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.None)) { fSerializer.Serialize(fStream, this); } } The problem is that when the user does not have rights to the location on hard disk, this function will not throw me any exception and do not save my file. For example saving to "C:\test.xml" act like nothing happened. And I would like to know if the file has not been saved and it would be good to know the reason why. I know that I could check if the file on given location exists and throw an exception manualy but shouldn't this be done by the XmlSerializer or FileStream itself? Thanks for your time

    Read the article

  • Is there a standard .NET exception to throw when a class doesn't implement a required attribute?

    - by a typing monkey
    Suppose I want to throw a new exception when invoking a generic method with a type that doesn't have a required attribute. Is there a .NET exception that's appropriate for this situation, or, more likely, one that would be a suitable ancestor for a custom exception? For example: public static class ClassA { public static T DoSomething<T>(string p) { Type returnType = typeof(T); object[] typeAttributes = returnType.GetCustomAttributes(typeof(SerializableAttribute), true); if ((typeAttributes == null) || (typeAttributes.Length == 0)) { // Is there an exception type in the framework that I should use/inherit from here? throw new Exception("This class doesn't support blah blah blah"); // Maybe ArgumentException? That doesn't seem to fit right. } } } Thanks.

    Read the article

  • Turn class "Interfaceable"

    - by scooterman
    Hi folks, On my company system, we use a class to represent beans. It is just a holder of information using boost::variant and some serialization/deserialization stuff. It works well, but we have a problem: it is not over an interface, and since we use modularization through dlls, building an interface for it is getting very complicated, since it is used in almost every part of our app, and sadly interfaces (abstract classes ) on c++ have to be accessed through pointers, witch makes almost impossible to refactor the entire system. Our structure is: dll A: interface definition through abstract class dll B: interface implementation there is a painless way to achieve that (maybe using templates, I don't know) or I should forget about making this work and simply link everything with dll B? thanks Edit: Here is my example. this is on dll A BeanProtocol is a holder of N dataprotocol itens, wich are acessed by a index. class DataProtocol; class UTILS_EXPORT BeanProtocol { public: virtual DataProtocol& get(const unsigned int ) const { throw std::runtime_error("Not implemented"); } virtual void getFields(std::list<unsigned int>&) const { throw std::runtime_error("Not implemented"); } virtual DataProtocol& operator[](const unsigned int ) { throw std::runtime_error("Not implemented"); } virtual DataProtocol& operator[](const unsigned int ) const { throw std::runtime_error("Not implemented"); } virtual void fromString(const std::string&) { throw std::runtime_error("Not implemented"); } virtual std::string toString() const { throw std::runtime_error("Not implemented"); } virtual void fromBinary(const std::string&) { throw std::runtime_error("Not implemented"); } virtual std::string toBinary() const { throw std::runtime_error("Not implemented"); } virtual BeanProtocol& operator=(const BeanProtocol&) { throw std::runtime_error("Not implemented"); } virtual bool operator==(const BeanProtocol&) const { throw std::runtime_error("Not implemented"); } virtual bool operator!=(const BeanProtocol&) const { throw std::runtime_error("Not implemented"); } virtual bool operator==(const char*) const { throw std::runtime_error("Not implemented"); } virtual bool hasKey(unsigned int field) const { throw std::runtime_error("Not implemented"); } }; the other class (named GenericBean) implements it. This is the only way I've found to make this work, but now I want to turn it in a truly interface and remove the UTILS_EXPORT (which is an _declspec macro), and finally remove the forced linkage of B with A.

    Read the article

  • File Output using Gforth

    - by sheepez
    As a first project I have been writing a short program to render the Mandelbrot fractal. I have got to the point of trying to output my results to a file ( e.g. .bmp or .ppm ) and got stuck. I have not really found any examples of exactly what I am trying to do, but I have found two examples of code to copy from one file to another. The examples in the Gforth documentation ( Section 3.27 ) did not work for me ( winXP ) in fact they seemed to open and create files but not write to files properly. This is the Gforth documentation example that copies the contents of one file to another: 0 Value fd-in 0 Value fd-out : open-input ( addr u -- ) r/o open-file throw to fd-in ; : open-output ( addr u -- ) w/o create-file throw to fd-out ; s" foo.in" open-input s" foo.out" open-output : copy-file ( -- ) begin line-buffer max-line fd-in read-line throw while line-buffer swap fd-out write-line throw repeat ; I found this example ( http://rosettacode.org/wiki/File_IO#Forth ) which does work. The main problem is that I can't isolate the part that writes to a file and have it still work. The main confusion is that r doesn't seem to consume TOS as I might expect. : copy-file2 ( a1 n1 a2 n2 -- ) r/o open-file throw >r w/o create-file throw r> begin pad maxstring 2 pick read-file throw ?dup while pad swap 3 pick write-file throw repeat close-file throw close-file throw ; \ Invoke it like this: s" output.txt" s" input.txt" copy-file I would be very grateful if someone could explain exactly how the open, create read and write -file words actually work, as my investigation keeps resulting in somewhat bizarre stacks. Any clues as to why the Gforth examples do not work might help too. In summary, I want to output from Gforth to a file and so far have been thwarted. Can anyone offer any help? Thank you Vijay, I think that I understand the example that you gave. However when I try to use something like this ( which I think is similar ): 0 value test-file : write-test s" testfile.out" w/o create-file throw to test-file s" test text" test-file write-line ; I get ok but nothing is put into the file, have I made a mistake? It seems that the problem was due to not flushing the relevant buffers or explicitly closing the file. Adding something like test-file flush-file throw or test-file close-file throw between write-line and ; makes it work. Thanks again Vijay for helping.

    Read the article

  • Optimizing a thread safe Java NIO / Serialization / FIFO Queue [migrated]

    - by trialcodr
    I've written a thread safe, persistent FIFO for Serializable items. The reason for reinventing the wheel is that we simply can't afford any third party dependencies in this project and want to keep this really simple. The problem is it isn't fast enough. Most of it is undoubtedly due to reading and writing directly to disk but I think we should be able to squeeze a bit more out of it anyway. Any ideas on how to improve the performance of the 'take'- and 'add'-methods? /** * <code>DiskQueue</code> Persistent, thread safe FIFO queue for * <code>Serializable</code> items. */ public class DiskQueue<ItemT extends Serializable> { public static final int EMPTY_OFFS = -1; public static final int LONG_SIZE = 8; public static final int HEADER_SIZE = LONG_SIZE * 2; private InputStream inputStream; private OutputStream outputStream; private RandomAccessFile file; private FileChannel channel; private long offs = EMPTY_OFFS; private long size = 0; public DiskQueue(String filename) { try { boolean fileExists = new File(filename).exists(); file = new RandomAccessFile(filename, "rwd"); if (fileExists) { size = file.readLong(); offs = file.readLong(); } else { file.writeLong(size); file.writeLong(offs); } } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } channel = file.getChannel(); inputStream = Channels.newInputStream(channel); outputStream = Channels.newOutputStream(channel); } /** * Add item to end of queue. */ public void add(ItemT item) { try { synchronized (this) { channel.position(channel.size()); ObjectOutputStream s = new ObjectOutputStream(outputStream); s.writeObject(item); s.flush(); size++; file.seek(0); file.writeLong(size); if (offs == EMPTY_OFFS) { offs = HEADER_SIZE; file.writeLong(offs); } notify(); } } catch (IOException e) { throw new RuntimeException(e); } } /** * Clears overhead by moving the remaining items up and shortening the file. */ public synchronized void defrag() { if (offs > HEADER_SIZE && size > 0) { try { long totalBytes = channel.size() - offs; ByteBuffer buffer = ByteBuffer.allocateDirect((int) totalBytes); channel.position(offs); for (int bytes = 0; bytes < totalBytes;) { int res = channel.read(buffer); if (res == -1) { throw new IOException("Failed to read data into buffer"); } bytes += res; } channel.position(HEADER_SIZE); buffer.flip(); for (int bytes = 0; bytes < totalBytes;) { int res = channel.write(buffer); if (res == -1) { throw new IOException("Failed to write buffer to file"); } bytes += res; } offs = HEADER_SIZE; file.seek(LONG_SIZE); file.writeLong(offs); file.setLength(HEADER_SIZE + totalBytes); } catch (IOException e) { throw new RuntimeException(e); } } } /** * Returns the queue overhead in bytes. */ public synchronized long overhead() { return (offs == EMPTY_OFFS) ? 0 : offs - HEADER_SIZE; } /** * Returns the first item in the queue, blocks if queue is empty. */ public ItemT peek() throws InterruptedException { block(); synchronized (this) { if (offs != EMPTY_OFFS) { return readItem(); } } return peek(); } /** * Returns the number of remaining items in queue. */ public synchronized long size() { return size; } /** * Removes and returns the first item in the queue, blocks if queue is empty. */ public ItemT take() throws InterruptedException { block(); try { synchronized (this) { if (offs != EMPTY_OFFS) { ItemT result = readItem(); size--; offs = channel.position(); file.seek(0); if (offs == channel.size()) { truncate(); } file.writeLong(size); file.writeLong(offs); return result; } } return take(); } catch (IOException e) { throw new RuntimeException(e); } } /** * Throw away all items and reset the file. */ public synchronized void truncate() { try { offs = EMPTY_OFFS; file.setLength(HEADER_SIZE); size = 0; } catch (IOException e) { throw new RuntimeException(e); } } /** * Block until an item is available. */ protected void block() throws InterruptedException { while (offs == EMPTY_OFFS) { try { synchronized (this) { wait(); file.seek(LONG_SIZE); offs = file.readLong(); } } catch (IOException e) { throw new RuntimeException(e); } } } /** * Read and return item. */ @SuppressWarnings("unchecked") protected ItemT readItem() { try { channel.position(offs); return (ItemT) new ObjectInputStream(inputStream).readObject(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }

    Read the article

  • How to tell the Session to throw the error query[NHibernate]?

    - by xandy
    I made a test class against the repository methods shown below: public void AddFile<TFileType>(TFileType FileToAdd) where TFileType : File { try { _session.Save(FileToAdd); _session.Flush(); } catch (Exception e) { if (e.InnerException.Message.Contains("Violation of UNIQUE KEY")) throw new ArgumentException("Unique Name must be unique"); else throw e; } } public void RemoveFile(File FileToRemove) { _session.Delete(FileToRemove); _session.Flush(); } And the test class: try { Data.File crashFile = new Data.File(); crashFile.UniqueName = "NonUniqueFileNameTest"; crashFile.Extension = ".abc"; repo.AddFile(crashFile); Assert.Fail(); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(ArgumentException)); } // Clean up the file Data.File removeFile = repo.GetFiles().Where(f => f.UniqueName == "NonUniqueFileNameTest").FirstOrDefault(); repo.RemoveFile(removeFile); The test fails. When I step in to trace the problem, I found out that when I do the _session.flush() right after _session.delete(), it throws the exception, and if I look at the sql it does, it is actually submitting a "INSERT INTO" statement, which is exactly the sql that cause UNIQUE CONSTRAINT error. I tried to encapsulate both in transaction but still same problem happens. Anyone know the reason?

    Read the article

  • Why might the Large Object Heap grow rather than throw an exception?

    - by Unsliced
    In a previous question I asked possible programatic ways of maximising the largest block allocatable on the LOH. I'm still seeing the problems, but now I'm trying to get my head around why the LOH seems to grow and shrink in size, yet I'm still seeing OutOfMemoryExceptions that tally with what others have reported as being due to LOH fragmentation. Why might one call to, for example, StringBuilder.EnsureCapacity throw an OutOfMemoryException for me, but another call from somewhere else result in the LOH expanding in size (according to the performance counters, it is growing and shrinking)?

    Read the article

  • Is there a simple way to let a layer throw an smooth shadow?

    - by mystify
    I was drawing a path into a layer. Lets say I can't access that drawing code in any way, because it comes from a compiled lib. Now I want to let that layer throw a shadow which matches the shape of its irregular content shape. Is there an easy way to do it? Or must I draw like 20 of those layers and scale them up on every iteration, adjusting their alpha and letting the GPU do the extraordinarily heavy compositing?

    Read the article

  • when does java.util.zip.ZipFile.close() throw IOException?

    - by sk
    Under what circumstances would java.util.zip.ZipFile.close() throw an IOException? Its method signature indicates that it can be thrown, but from the source code there doesn't seem to be any place where this could happen, unless it's in native code. What corrective action, if any, could be taken at the point where that exception is caught?

    Read the article

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