Xer0botXer0

Error Handling Question

Recommended Posts

Xer0botXer0    120

Hi guys,

So I'm looking at another developers project for learning purposes and I'm just moving through the code so I can get an understanding of what's happening and how to write my own version of it. And the first thing I'm looking at is the 'try ..catch' statement. From what I can tell the purpose of try catch is to try a block of code and if an exception occurs then catch it, In this example I'm not sure how catching is actually working.

try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
        }

I've also seen some basic examples where 0 is divided by a value and it's suppose to throw an Exception, the person then draws a line to say hey you can't divide like that. But in this case what will happen ?

I think more importantly, if an error occurs, does the program crash, and whether or not it crashes will I see a message in Eclipse console telling me what caused the error ? 

And then, from what I've read some peoples approach is to determine what exceptions/errors may occur and then change their code to prevent that from happening. 

These questions will help me understand whether or not I can take the following approach, code, run the program, attempt all possible interactions, when an error occurs see what it says in the console or rather see what interaction I did that caused it then modify the code to prevent that from happening, instead of catching exceptions.

Update:

I looked up exceptions a bit, I see that InterruptedException is a specific exception that throws when a sleeping thread is interrupted using the interrupt(); method. And that I don't see interrupt being used in the project then the exception is actually not required. 

Edited by Xer0botXer0
Update

Share this post


Link to post
Share on other sites
dcoolllx    2

Your question seems to be a little broad. Exception in general are when the program/computer encounters a situation that it does not know how to handle ie. dividing by 0. in this case, an Exception object is created and "thrown" to an Exception handler. if no exception handler is found within the program the program will exit(crash). when Designing a system a good programmer will anticipate when an exception will occur and reroute the program to prevent a crash. its important to realize that there are two types of exceptions. checked and unchecked. check exceptions are caused by programmer error and are caught by the interpreter/compiler. these types of exceptions will prevent a program from compiling. the second, uncheck, is also called a runtime error/exception. these are caused by the user giving an input that was unexpected or that the program does not know how to handle. these types are Not inherently bad. the one you are looking at may be a little confusing if you don't understand threads and concurrency. In this case the programmer has commanded a thread to wait/sleep for a certain amount of time. If in the event that some outside force like the OS, or even the user interrupts this thread it will throw an exception which the programmer can use to know that his thread is no longer sleeping. other examples of exception that are not necessarily bad; a FileNotFoundException can be used to check for the existence of a file before writing to it. after the programmer catches this exception he may, for example, prompt the user to create a new file before writing.

Share this post


Link to post
Share on other sites
Kylotan    10006

"In this example I'm not sure how catching is actually working." - In this example the catch doesn't have to do anything. It is just there so that the exception is handled and doesn't propagate down to the caller. Exceptions that don't get handled cause the program to terminate. So when you write code that calls a function, you need to consider whether it can throw exceptions that you need to handle - like the writer of this code did, knowing that Thread.sleep can throw InterruptedException. Note that exceptions aren't always errors, such as in this case. It's just an unusual condition that needs handling.

If you can modify code to prevent the possibillity of certain exceptions being raised, that is usually preferable. But exceptions exist to handle conditions that you can't prevent, or events that you couldn't easily predict.

Share this post


Link to post
Share on other sites
Kylotan    10006

In Java it's useful to have that there as it forces you to write good code. If you have "throws xException" then you're not allowed to let other exceptions be thrown out of the function - which is good news for callers of that function, as they know they only ever have to handle xExceptions. This is entirely about which exceptions can be thrown out of the method - it has no relation to try/catch blocks inside the method. However, you may need to add catch blocks in order to conform to the exception specification, as you will need to handle all other exceptions.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Similar Content

    • By grumpyOldDude
      As my project is beginning to take shape, most of the problems I've encountered, I've been able to solve, but this latest one cunningly beats me, not because of any complexities but  because I don't know whats going on under the hood of the parser.
      I am using a pattern matcher() Pattern.compile("\\d+");  - (in JAVA) - to extract and read floats,   but there were problems as white spaces are being interpreted as 0.0
      808.00.0472.00.036.00.0202.00.018.00.024.00.0 782.00.096.00.036.00.0202.00.018.00.024.00.0 909.00.01028.00.036.00.0202.00.018.00.024.00.0 931.00.01149.00.036.00.0202.00.018.00.024.00.0 but should, correctly, be something like this 808.0 472.0 36.0 202.0 18.0 24.0 782.0 96.0 36.0 202.0 18.0 24.0 909.0 1028.0 36.0 202.0 18.0 24.0 931.0 1149.0 36.0 202.0 18.0 24.0 It was wrong because it was making white space to be 0.0 As said It was wrong because it was making white space to be 0.0
      My quick fix was to use an if statement that exclude 0.0.  
      Well I got away with it until the inevitable began to happen,- some of the real data started turning out to be 0.0, so my if statement was excluding the  real data from being read.  Any help on how to get this fixed?  I need white space to be read as white space not as 0.0 
      public void readDataFromSelectedTextFile( File fPathplusName ){ List<Float> numbers = new LinkedList<Float>(); try { bufferedReader = new BufferedReader(new FileReader(fPathplusName)); while ((stringObjectData = bufferedReader.readLine()) != null){ Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(stringObjectData); while (m.find()) { numbers.add(Float.parseFloat(m.group())); } } ListIterator<Float> floatIterator = numbers.listIterator(); int i=0, t=7, n=0; float s, size=0; while( floatIterator.hasNext() ){ if( (s = floatIterator.next()) > 0 ){ ... ... plenty of good coding here ... ... } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }/**/ }  
    • By JesterCall
      First of all sorry, for my terrible writing im not good with it, but there is no need to hold back with your answers i only have problems when it comes to writing. 
      I started to write my own 2D Game Engine in Java for practice(and for fun) reasons. Until now i've made very good progress but i got a problem, which i got stuck on. 
      I started to build a basic tile picker (left click: setTile | right click: getTile). So far so fine, but here is the problem. The further away my mouse gets from the upper left corner of the screen, the more inaccurate the tilepicker gets.
      In the picture, you can see the overall tile i clicked on (black cross) and the accurat point (orange dot). This would get me the blue tile underneath.
       

       
      This is the code i used to translate the mouse coordinates to tile coordinates. 
      if(input.mouseleft.isClicked()) { tx = (int) (Math.floor(world.getCamera().getX() + input.getMouseX()) / world.getTileSize()); ty = (int) (Math.floor(world.getCamera().getY() + input.getMouseY()) / world.getTileSize()); // Checks if the coordinates are within the tilemap if(tx >= 0 && tx <= world.getWidth() && ty >= 0 && ty <= world.getHeight() ) world.setTile(holdtileid, tx, ty); }  
      I hope somone can help me and thanks in advance.
       
       
    • By janek29
      Hi,
      I want to present my game called "What's that?". I developed it using Android Studio.
      Download from here: https://play.google.com/store/apps/details?id=com.threemgames.whatsthat&hl=en
       
      Youtube video gameplay:
       
       

       
       
      It contains Google Play leadboards so you can compare your score with your friends.
      It is an easy game in which u have to use your head and guess the names of 50 objects - things, animals or activities.
      Use your imagination and on the basis of a few strokes deduce what may be in the drawing.
      Open your mind because it will allow you to put together lines, dots and bows into one. When you are sure of what the drawing represents, enter the name using the letters at the bottom. If you have doubts or can not guess, use the tips. So to the work, wake up your mind, duck your mind in the missing elements and solve the mystery. Let the imagination be with you!
       
      * 50 different puzzles
      * An amazing quiz that stimulates the imagination
      * Different degrees of puzzle difficulty in the quiz
       
      It is FREE!
       
      I am waiting for your comments .
       
      Please, give me feedback. If you notice any bugs please tell me .
       
      Thanks !
    • By mungee
      https://www.youtube.com/playlist?list=PLx2OWCj5oxNPuqz2o3Tk8exOQtAAtIeRd

    • By imontheverge
      Im trying to create a simple " give order to Sprite, make Sprite do thing" game much like rimworld or oxygen not included.
      So far I have two controllers type objects, on for the player and one for each Sprite. When a Sprite is selected, the player controller takes a reference of the Sprite and sets a Boolean variable hasMoveOrder to true when the player clicks on a spot.
      My code right now is filled with if/else statements in order to get this to work. Once I add more work orders like digging, building, etc, a thousand if statements starts to get sloppy. The question is what kind of data structure or algorithms can I use to make this more efficient? Would an enumeration of the Sprite states be fine and just switch through them when the Sprite gets a new work order? Or would something more complex like a state machine make sense?
  • Popular Now