Search Results

Search found 4737 results on 190 pages for 'nested exceptions'.

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

  • "Programming error" exceptions - Is my approach sound?

    - by Medo42
    I am currently trying to improve my use of exceptions, and found the important distinction between exceptions that signify programming errors (e.g. someone passed null as argument, or called a method on an object after it was disposed) and those that signify a failure in the operation that is not the caller's fault (e.g. an I/O exception). As far as I understand, it makes little sense for an immediate caller to actually handle programming error exceptions, he should instead assure that the preconditions are met. Only "outer" exception handlers at task boundaries should catch them, so they can keep the system running if a task fails. In order to ensure that client code can cleanly catch "failure" exceptions without catching error exceptions by mistake, I create my own exception classes for all failure exceptions now, and document them in the methods that throw them. I would make them checked exceptions in Java. Now I have a few questions: Before, I tried to document all exceptions that a method could throw, but that sometimes creates an unwiedly list that needs to be documented in every method up the call chain until you can show that the error won't happen. Instead, I document the preconditions in the summary / parameter descriptions and don't even mention what happens if they are not met. The idea is that people should not try to catch these exceptions explicitly anyway, so there is no need to document their types. Would you agree that this is enough? Going further, do you think all preconditions even need to be documented for every method? For example, calling methods in IDisposable objects after calling Dispose is an error, but since IDisposable is such a widely used interface, can I just assume a programmer will know this? A similar case is with reference type parameters where passing null makes no conceivable sense: Should I document "non-null" anyway? IMO, documentation should only cover things that are not obvious, but I am not sure where "obvious" ends.

    Read the article

  • Throwing and catching exceptions in the same function/method

    - by usr
    I've written a function that asks a user for input until user enters a positive integer (a natural number). Somebody said I shouldn't throw and catch exceptions in my function and should let the caller of my function handle them. I wonder what other developers think about this. I'm also probably misusing exceptions in the function. Here's the code in Java: private static int sideInput() { int side = 0; String input; Scanner scanner = new Scanner(System.in); do { System.out.print("Side length: "); input = scanner.nextLine(); try { side = Integer.parseInt(input); if (side <= 0) { // probably a misuse of exceptions throw new NumberFormatException(); } } catch (NumberFormatException numFormExc) { System.out.println("Invalid input. Enter a natural number."); } } while (side <= 0); return side; } I'm interested in two things: Should I let the caller worry about exceptions? The point of the function is that it nags the user until the user enters a natural number. Is the point of the function bad? I'm not talking about UI (user not being able to get out of the loop without proper input), but about looped input with exceptions handled. Would you say the throw statement (in this case) is a misuse of exceptions? I could easily create a flag for checking validity of the number and output the warning message based on that flag. But that would add more lines to the code and I think it's perfectly readable as it is. The thing is I often write a separate input function. If user has to input a number multiple times, I create a separate function for input that handles all formatting exceptions and limitations.

    Read the article

  • How to void checked exceptions in Java?

    - by deamon
    I consider checked exception for a design mistake in the Java language. They lead to leaky abstractions and a lot of clutter in the code. It seems that they force the programmer to handle exceptions early although they are in most cases better handled lately. So my question is how to avoid checked exception? My idea is to execute the actual code inside an exception translator using lambda expressions. Example: ExceptionConverter.convertToRuntimeException(() => { // do things that could throw checked exceptions here }); If for example a IOException occurs it gets rethrown as an exception with the same name but from a different class hierarchy (based on RuntimeException). This approach would effectivly remove the need to handle or declare checked exceptions. Exceptions could then be handled where and if it makes sense. Another solution would be to declare IOException throws Exception on each method. What do you think which solution is better? Do you know any better approach to avoid (suppress) checked exceptions in Java?

    Read the article

  • Decision for Unchecked Exceptions in Scala

    - by Jatin
    As a java programmer, I have always been critical of Unchecked Exceptions. Mostly programmers use it as an en-route to coding easiness only to create trouble later. Also the programs (though untidy) with checked exceptions are much robust compared to unchecked counterparts. Surprisingly in Scala, there is nothing called Checked Exceptions. All the Java checked and unchecked are unchecked in Scala. What is the motivation behind this decision? For me it opens wide range of problems when using any external code. And if by chance the documentation is poor, it results in KILL.

    Read the article

  • Returning null vs Throwing exceptions

    - by Svish
    Is in a bit of disagreement with a more experienced developer on this issue, and was wondering what you guys here think about this. Environment is Java, EJB 3, services, etc. The code I wrote calls a service to get things and to create things. Problem was that I got null pointer exceptions in places that didn't make sense. For example when I asked the service to create an object, I got null back. And when I tried to look up an object with an id I knew existed, I still got null back. Was like it was ignoring me. Spent some time trying to figure out what was wrong in my code (since I'm less experienced I usually assume I have messed up). Turns out the reason was security. If the user principal using my service didn't have the right permissions to use the service I called from my service, then that service simply returned null. The services that are here already are usually not documented either, so this is just something you have to know... somehow... So here is the thing: I mean that this is rather confusing as a developer interacting with this service. To me it would make much more sense if that service thew an exception which would tell me that hey, you don't have the proper permissions to get info about this thing or to create this new thing. I would then immediately know why my service wasn't working as expected. However, he argued that asking is not wrong. Exceptions should only be thrown when there is an error and asking for a thing is not an error. Even if you don't have permission to "see" that the thing you asked for. The things are often looked up in a GUI by users and for those users not having the right permissions, these things simply "do not exist". So, in short: Asking is not wrong, hence no exception. Get methods return null because to those users those things "doesn't exist". Create methods return null because nothing was created, since the user wasn't allowed to create anything. So, what do you guys think? Is this normal and/or good practice? I prefer exceptions as I prefer throwing and catching exceptions because I find it much easier to know what's going on. So I would for example also prefer to throw a NotFoundException if you asked for an id which didn't exist, rather than returning null. Anyways, just curious to what others think about this as I'm not the most experienced developer yet.

    Read the article

  • How to avoid throwing vexing exceptions?

    - by Mike
    Reading Eric Lippert's article on exceptions was definitely an eye opener on how I should approach exceptions, both as the producer and as the consumer. However, I'm still struggling to define a guideline regarding how to avoid throwing vexing exceptions. Specifically: Suppose you have a Save method that can fail because a) Somebody else modified the record before you, or b) The value you're trying to create already exists. These conditions are to be expected and not exceptional, so instead of throwing an exception you decide to create a Try version of your method, TrySave, which returns a boolean indicating if the save succeeded. But if it fails, how will the consumer know what was the problem? Or would it be best to return an enum indicating the result, kind of Ok/RecordAlreadyModified/ValueAlreadyExists? With integer.TryParse this problem doesn't exist, since there's only one reason the method can fail. Is the previous example really a vexing situation? Or would throwing an exception in this case be the preferred way? I know that's how it's done in most libraries and frameworks, including the Entity framework. How do you decide when to create a Try version of your method vs. providing some way to test beforehand if the method will work or not? I'm currently following these guidelines: If there is the chance of a race condition, then create a Try version. This prevents the need for the consumer to catch an exogenous exception. For example, in the Save method described before. If the method to test the condition pretty much would do all that the original method does, then create a Try version. For example, integer.TryParse(). In any other case, create a method to test the condition.

    Read the article

  • Is catching general exceptions really a bad thing?

    - by Bob Horn
    I typically agree with most code analysis warnings, and I try to adhere to them. However, I'm having a harder time with this one: CA1031: Do not catch general exception types I understand the rationale for this rule. But, in practice, if I want to take the same action regardless of the exception thrown, why would I handle each one specifically? Furthermore, if I handle specific exceptions, what if the code I'm calling changes to throw a new exception in the future? Now I have to change my code to handle that new exception. Whereas if I simply caught Exception my code doesn't have to change. For example, if Foo calls Bar, and Foo needs to stop processing regardless of the type of exception thrown by Bar, is there any advantage in being specific about the type of exception I'm catching?

    Read the article

  • Designing exceptions for conversion failures

    - by Mr.C64
    Suppose there are some methods to convert from "X" to "Y" and vice versa; the conversion may fail in some cases, and exceptions are used to signal conversion errors in those cases. Which would be the best option for defining exception classes in this context? A single XYConversionException class, with an attribute (e.g. an enum) specifying the direction of the conversion (e.g. ConversionFromXToY, ConversionFromYToX). A XYConversionException class, with two derived classes ConversionFromXToYException and ConversionFromYToXException. ConversionFromXToYException and ConversionFromYToXException classes without a common base class.

    Read the article

  • if/else statements or exceptions

    - by Thaven
    I don't know, that this question fit better on this board, or stackoverflow, but because my question is connected rather to practices, that some specified problem. So, consider an object that does something. And this something can (but should not!) can go wrong. So, this situation can be resolved in two way: first, with exceptions: DoSomethingClass exampleObject = new DoSomethingClass(); try { exampleObject.DoSomething(); } catch (ThisCanGoWrongException ex) { [...] } And second, with if statement: DoSomethingClass exampleObject = new DoSomethingClass(); if(!exampleObject.DoSomething()) { [...] } Second case in more sophisticated way: DoSomethingClass exampleObject = new DoSomethingClass(); ErrorHandler error = exampleObject.DoSomething(); if (error.HasError) { if(error.ErrorType == ErrorType.DivideByPotato) { [...] } } which way is better? In one hand, I heard that exception should be used only for real unexpected situations, and if programist know, that something may happen, he should used if/else. In second hand, Robert C. Martin in his book Clean Code Wrote, that exception are far more object oriented, and more simple to keep clean.

    Read the article

  • When to use custom exceptions vs. existing exceptions vs. generic exceptions

    - by Ryan Elkins
    I'm trying to figure out what the correct form of exceptions to throw would be for a library I am writing. One example of what I need to handle is logging a user in to a station. They do this by scanning a badge. Possible things that could go wrong include: Their badge is deactivated They don't have permission to work at this station The badge scanned does not exist in the system They are already logged in to another station elsewhere The database is down Internal DB error (happens sometimes if the badge didn't get set up correctly) An application using this library will have to handle these exceptions one way or another. It's possible they may decide to just say "Error" or they may want to give the user more useful information. What's the best practice in this situation? Create a custom exception for each possibility? Use existing exceptions? Use Exception and pass in the reason (throw new Exception("Badge is deactivated.");)? I'm thinking it's some sort of mix of the first two, using existing exceptions where applicable, and creating new ones where needed (and grouping exceptions where it makes sense).

    Read the article

  • Where should I handle fatal exceptions

    - by Puckl
    For example, I have a controller that loads a file and hands it over to the processing. Should I handle the exception in the file loader and return Null if something is wrong, or should I throw the exception and handle it in the controller? Without the file the rest of the program can´t work. Where should I handle a exception that shuts down the program properly? I want to shut down an Android application properly.

    Read the article

  • rails nested attributes

    - by user342798
    I am using rails 3.0.0.beta3 and I am trying to implement form with nested attributes using :accepts_nested_attributes_for. My form is nested to three levels: Survey Question Answer. Survey has_many Questions, and Question has many Answers. Inside the Survey model, there is :accepts_nested_attributes_for :questions and inside the question mode, there is :accepts_nested_attributes_for :answers Everything is working fine except when I add a new answer to an existing question, it doesn't get created. However, if I make changes to the corresponding question while creating the answer, I can successfully create the answer. This example is exactly similar to a railscast: http://railscasts.com/episodes/197-nested-model-form-part-2 but doesn't work in rails3 (at least in my case). Please let me know if there is any issue with nested attributes in Rails 3. Thanks in advance.

    Read the article

  • Which are the most frequent exceptions thrown in Java applications? [on hold]

    - by Chris
    1. Do you know of any statistics about the frequency of exceptions (checked and unchecked) thrown at runtime in typical Java applications? for example: NullPointerException: 25% of all exceptions ClassCastException: 15% of all exceptions etc. 2. Which are the most frequent exceptions according to your own experiences? 3. Would you agree that the NullPointerException is generally the most often thrown exception? I am asking this question in the context of the compiler development of the PPL programming language (www.practical-programming.org). The goal is to auto-detect a maximum of frequent exceptions at compile-time. For example, detecting all potential NullPointerExceptions at compile-time leads to null-safe software which is more reliable.

    Read the article

  • undefined method `build_users' with nested models

    - by Cédric
    I've got into trouble with nested attributes. Here is my Account model : class Account < ActiveRecord::Base has_many :products has_many :blogs has_many :openings has_many :users has_one :logo, :class_name => "AccountPicture" has_one :address, :class_name => "AccountAddress" has_and_belongs_to_many :options accepts_nested_attributes_for :logo, :allow_destroy => true accepts_nested_attributes_for :address, :allow_destroy => true accepts_nested_attributes_for :users, :allow_destroy => true end And here is my User model : class User < ActiveRecord::Base belongs_to :account end As you can see, Account accepts nested attributes for logo, address, and users. While testing, i can use nested attributes for logo and address, but not for user. a = Account.new => #<Account id: nil, hostname: nil, subdomain: nil, name: nil, description: nil, base_line: nil, footer: nil, phone_number: nil, mobile_number: nil, email_address: nil, created_at: nil, updated_at: nil> # building the address works fine >> a.build_address => #<AccountAddress id: nil, account_id: nil, country: nil, state: nil, county: nil, city: nil, suburb: nil, zipcode: nil, street: nil, streetno: nil, longitude: nil, latitude: nil, error_code: nil> # building the users fails >> a.build_users NoMethodError: undefined method `build_users' for #<Account:0x7f6862a5f948> from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/attribute_methods.rb:260:in `method_missing' from (irb):2 Thus, in my views, when i use the nested forms, i got this error back : User(#69850615730460) expected, got Array(#69850664775200) Any help would be appreciated. Thanks.

    Read the article

  • Are there any real-world cases for C++ without exceptions?

    - by Martin
    In When to use C over C++, and C++ over C? there is a statement wrt. to code size / C++ exceptions: Jerry answers (among other points): (...) it tends to be more difficult to produce truly tiny executables with C++. For really small systems, you're rarely writing a lot of code anyway, and the extra (...) to which I asked why that would be, to which Jerry responded: the main thing is that C++ includes exception handling, which (at least usually) adds some minimum to the executable size. Most compilers will let you disable exception handling, but when you do the result isn't quite C++ anymore. (...) which I do not really doubt on a technical real world level. Therefore I'm interested (purely out of curiosity) to hear from real world examples where a project chose C++ as a language and then chose to disable exceptions. (Not just merely "not use" exceptions in user code, but disable them in the compiler, so that you can't throw or catch exceptions.) Why does a project chose to do so (still using C++ and not C, but no exceptions) - what are/were the (technical) reasons? Addendum: For those wishing to elaborate on their answers, it would be nice to detail how the implications of no-exceptions are handled: STL collections (vector, ...) do not work properly (allocation failure cannot be reported) new can't throw Constructors cannot fail

    Read the article

  • Alternative to Nested Loop For Comparison

    - by KGVT
    I'm currently writing a program that needs to compare each file in an ArrayList of variable size. Right now, the way I'm doing this is through a nested code loop: if(tempList.size()>1){ for(int i=0;i<=tempList.size()-1;i++) //Nested loops. I should feel dirty? for(int j=i+1;j<=tempList.size()-1;j++){ //*Gets sorted. System.out.println(checkBytes(tempList.get(i), tempList.get(j))); } } I've read a few differing opinions on the necessity of nested loops, and I was wondering if anyone had a more efficient alternative. At a glance, each comparison is going to need to be done, either way, so the performance should be fairly steady, but I'm moderately convinced there's a cleaner way to do this. Any pointers?

    Read the article

  • A couple of questions on exceptions/flow control and the application of custom exceptions

    - by dotnetdev
    1) Custom exceptions can help make your intentions clear. How can this be? The intention is to handle or log the exception, regardless of whether the type is built-in or custom. The main reason I use custom exceptions is to not use one exception type to cover the same problem in different contexts (eg parameter is null in system code which may be effect by an external factor and an empty shopping basket). However, the partition between system and business-domain code and using different exception types seems very obvious and not making the most of custom exceptions. Related to this, if custom exceptions cover the business exceptions, I could also get all the places which are sources for exceptions at the business domain level using "Find all references". Is it worth adding exceptions if you check the arguments in a method for being null, use them a few times, and then add the catch? Is it a realistic risk that an external factor or some other freak cause could cause the argument to be null after being checked anyway? 2) What does it mean when exceptions should not be used to control the flow of programs and why not? I assume this is like: if (exceptionVariable != null) { } Is it generally good practise to fill every variable in an exception object? As a developer, do you expect every possible variable to be filled by another coder?

    Read the article

  • how to save nested form attributes to database

    - by siulamvictor
    I am not really understand how's the nested attributes work in Rails. I have 2 models, Accounts and Users. Accounts has_many Users. When a new user filled in the form, Rails reported User(#2164802740) expected, got Array(#2148376200) Is that Rails cannot read the nested attributes from the form? How can I fix it? How can I save the data from nested attributes form to database? Thanks all~ Here are the MVCs: Account Model class Account < ActiveRecord::Base has_many :users accepts_nested_attributes_for :users validates_presence_of :company_name, :message => "companyname is required." validates_presence_of :company_website, :message => "website is required." end User Model class User < ActiveRecord::Base belongs_to :account validates_presence_of :user_name, :message => "username too short." validates_presence_of :password, :message => "password too short." end Account Controller class AccountController < ApplicationController def new end def created end def create @account = Account.new(params[:account]) if @account.save redirect_to :action => "created" else flash[:notice] = "error!!!" render :action => "new" end end end Account/new View <h1>Account#new</h1> <% form_for :account, :url => { :action => "create" } do |f| %> <% f.fields_for :users do |ff| %> <p> <%= ff.label :user_name %><br /> <%= ff.text_field :user_name %> </p> <p> <%= ff.label :password %><br /> <%= ff.password_field :password %> </p> <% end %> <p> <%= f.label :company_name %><br /> <%= f.text_field :company_name %> </p> <p> <%= f.label :company_website %><br /> <%= f.text_field :company_website %> </p> <% end %> Account Migration class CreateAccounts < ActiveRecord::Migration def self.up create_table :accounts do |t| t.string :company_name t.string :company_website t.timestamps end end def self.down drop_table :accounts end end User Migration class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :user_name t.string :password t.integer :account_id t.timestamps end end def self.down drop_table :users end end Thanks everyone. :)

    Read the article

  • Why are exceptions considered better than explicit error testing?

    - by Richard Keller
    I often come across heated blog posts where the author uses the argument of "exceptions vs explicit error checking" to advocate their preferred language over some other language. The general consensus seems to be that languages which make use of exceptions are inherently better / cleaner than languages which rely heavily on error checking through explicit function calls. Is the use of exceptions considered better programming practice than explicit error checking, and if so, why?

    Read the article

  • What is a 'good number' of exceptions to implement for my library?

    - by Fuzz
    I've always wondered how many different exception classes I should implement and throw for various pieces of my software. My particular development is usually C++/C#/Java related, but I believe this is a question for all languages. I want to understand what is a good number of different exceptions to throw, and what the developer community expect of a good library. The trade-offs I see include: More exception classes can allow very fine grain levels of error handling for API users (prone to user configuration or data errors, or files not being found) More exception classes allows error specific information to be embedded in the exception, rather than just a string message or error code More exception classes can mean more code maintenance More exception classes can mean the API is less approachable to users The scenarios I wish to understand exception usage in include: During 'configuration' stage, which might include loading files or setting parameters During an 'operation' type phase where the library might be running tasks and doing some work, perhaps in another thread Other patterns of error reporting without using exceptions, or less exceptions (as a comparison) might include: Less exceptions, but embedding an error code that can be used as a lookup Returning error codes and flags directly from functions (sometimes not possible from threads) Implemented an event or callback system upon error (avoids stack unwinding) As developers, what do you prefer to see? If there are MANY exceptions, do you bother error handling them separately anyway? Do you have a preference for error handling types depending on the stage of operation?

    Read the article

  • Store PHP Exceptions in array

    - by Industrial
    Hi everyone, I am really not sure if this is the right way to go, since exceptions is really a fresh subject to me. Is it possible to catch multiple exceptions (let the execution of the script continue) and then store the exceptions in a array to be able to return all exceptions caused? By that said, it would be awesome to be able to use exceptions to more than just showing an error that kills the application (script) Thanks!

    Read the article

  • Nested class or not nested class?

    - by eriks
    I have class A and list of A objects. A has a function f that should be executed every X seconds (for the first instance every 1 second, for the seconds instance every 5 seconds, etc.). I have a scheduler class that is responsible to execute the functions at the correct time. What i thought to do is to create a new class, ATime, that will hold ptr to A instance and the time A::f should be executed. The scheduler will hold a min priority queue of Atime. Do you think it is the correct implementation? Should ATime be a nested class of the scheduler?

    Read the article

  • Nested attributes in the index view?

    - by user283179
    How would I show one of many nested objects in the index view class Album < ActiveRecord::Base has_many: photos accepts_nested_attributes_for :photos, :reject_if => proc { |a| a.all? { |k, v| v.blank?} } has_one: cover accepts_nested_attributes_for :cover end class Album Controller < ApplicationController layout "mini" def index @albums = Album.find(:all, :include => [:cover,]).reverse respond_to do |format| format.html # index.html.erb format.xml { render :xml => @albums } end end This is what I have so fare. I just want to show a cover for each album. Any info on this would be a massive help!!

    Read the article

  • has_one | nested attributes -

    - by user283179
    How would I show one of many nested objects in the index view class Album < ActiveRecord::Base has_many: photos accepts_nested_attributes_for :photos, :reject_if => proc { |a| a.all? { |k, v| v.blank?} } has_one: cover accepts_nested_attributes_for :cover end class Album Controller < ApplicationController layout "mini" def index @albums = Album.find(:all, :include => [:cover,]).reverse respond_to do |format| format.html # index.html.erb format.xml { render :xml => @albums } end end This is what I have so fare. I just want to show a cover for each album. Any info on this would be a massive help!!

    Read the article

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