Error Handling Question

Recommended Posts

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 {
} 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 on other sites

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 on other sites

"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 on other sites

Do I need to use "throws xException" in a method name, because I don't always see it used even though a try catch is used in the method ?

Share on other sites

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.

Create an account

Register a new account

• 10
• 9
• 14
• 16
• 10
• Similar Content

• Hey guys, I recently made this post, I recommend skimming for a quick gist and look at the results at the bottom of the post :
(I felt that post misrepresents what I've turned the language into as of right now, so here's this post.)

Where I described my proposition for a language to replace CSS (for good reasons, in my view).
Well I've gone ahead and create a Jar for it, and a GitHub wiki with a syntax specification (I recommend reading that instead of the syntax in the post I linked), and a quick-start guide to start making your own UX Library compatible with the language, if you want something a little less... shipoopi to work with. More organized, and robust.
Here is the GitHub for anyone who is interested:
https://github.com/BetterBe/Kiss-lang/wiki

• Hey guys, I am totally new to game dev and member here since today. I have been learning Java since 3 years now in school and have not done any bigger projects, but now i want to make the next step and start to develop a little game. Although i got a lot of ideas, i am not sure about a lot of basic game specific questions and i would appreciate it if you helped me there.

The game should be about an shift supervisor at a nuclear power plant, that has to deal with problems like replacing the fuel rods (where some complications could show up), an automated reactor shutdown or a generator on fire. I am not exactly sure how deep and real life compliant this game should be, but at least more realistic than just adjust the amount of coolant and how deep the control rods are in the water. The second problem here is that i have so many ideas that it would have more content than any game on the market and i can not decide what to include to my project.
Another point where i am not sure are the graphics (I heard that coding the game functions has prior 1 and the graphics should be done when the game functions are already working), I think 2d graphics would be easier to do, sure there are engines for 3d, but i have no experience with them and i do not instantly want to do a game with AAA graphics. Then i remembered the game X-COM: UFO Defense and i guess that type of graphic would be totally enough for my little simulator but i have no idea about the difficulty of making this (My only graphical experience is Window Builder). So there should be the control buttons and levers on the bottom of the interface, in the middle displays and the lights that you have to react to and on the upper side i would like to give a very very small and basic overview (more for your eyes than with real purposes) about your power plant where you for example can see smoke coming out of the cooling tower or a small fire burning down your transformer.

What do you think about my idea, what should i change, what do you think about my problems?
General feedback would be great as well. And no i do not want to learn C and do this in C, i want to do it with Java

And sorry if my English is not the best, it is not my mother tongue.

• The title is vague, so I'll explain.
I was frustrated with UI dev (in general), and even more-so when working with a application that needed OpenGL with embedded UI. What if I wanted to make a full application with OpenGL? (Custom game engine anyone?)
Well I did want to. And I'm working on it right now. But it started me onto making what I think is a great idea of a styling language;
I present KSS (pron. Kiss) The multitudes more programmable version of CSS.... (only for desktop dev)
/* It has all the 'normal' styling stuff, like you'd expect. */ elementName { /*This is a styling field.*/ font-color: rgb(0,0,0), font: "Calibri", font-size: 12px } .idName { color: rgba(255,255,255,0) } uiName : onMouse1Click{ color: vec3(0,0,0) } BUT
It also has some cool things. I've taken the liberty to add variables, templates (style inheritance), hierarchy-selection, events (as objects), native function calls, in-file functions.
var defaultColor: rgb(0,0,0) var number : 1.0 /*Types include: rgb, rgba, vec2, vec3, vec4, number, string, true, false, none (null), this*/ fun styleSomeStuff{ .buttons{ color: defaultColor, text-color: rgb(number,255,number) } } template buttonStyle{ color: rgb(255,255,0) } .buttons{ use: buttonStyle, otherTemplateName /*copies the templates styling field*/ color: defaultColor; } .buttons : onMouse1Click{ /* events not assigned as a value are initialized when read from file*/ styleSomeStuff();*/* call the in-file function*/ *nativeFunctionCall();/*call a native function that's binded*/ var a : 2; /*assign a variable, even if not initially defined.*/ } /*storing an event in a 'value' will allow you to operate on the event itself. It is only ran when 'connected', below.*/ val ON_CLICK2 = .buttons : onMouse2Click{ use: templateName } connect ON_CLICK2; disconnect ON_CLICK2; /*you can make a function to do the same.*/ fun connectStuff{ connect ON_CLICK2; }
But wait, you ask... what If I need to select items from a hierarchy? Surely using element names and id's couldn't be robust enough!
Well:
/*We use the > to indicate the item next element is a 'child' to itemA in the hierarchy*/ itemA > itemAChild : onMouse1Click{ } .itemId > .itemAChild > itemAChildsChild{ } /*want to get all children of the element at hand?*/ elementName > .any{ /*this will style all the elements children*/ } /*What about if we want to use conditional styling? Like if a variable or tag inside the element is or isnt something?*/ var hello : false; var goodbye : true; itemA [var hello = false, var goodbye != false] { /*passes*/ } itemA [@tagName = something]{ /*passes is the tag is equal to whatever the value u asked.*/ } The last things to note are event-pointers, how tagging works, 'this', and general workflow.
Tagging works (basically) the same as Unity, you say @tagName : tagValue inside a styling field to assign that element a tag that's referable in the application.
You have the ability to refer to any variable you assign within the styling sheet, from say.. source-code. The backend. As such, being able to set a variable to 'this' (the element being styled) allows you to operate with buttons who are currently in focus, or set the parent of an item to another element.
All elements are available to use as variables inside and outside the styling sheet, so an event can effectively parent an element or group of elements to a UI you specify. Ill show that in a figure below,
Event pointers are so that you can trigger an event with a UI component, but affect another, below-
/*We use the -> to point to a new element, or group of elements to style.*/ .buttons : onMouse1Click -> .buttons > childName{ visible : false parent: uiName; } /* In this case, we style something with the name "childName" whos parented to anything with the id 'buttons'. Likewise, we if there was a element with the name 'uiName', it would parent the childName element to it. */
Lastly: The results/workflow.
I'm in the process of building my first (serious) game engine after learning OpenGL, and I'm building it with Kotlin and Python. I can bind both Kotlin and Python functions for use inside the styling sheet, and although I didn't show the layout-language (cause its honestly not good), this is the result after a day of work so far, while using these two UI languages I've made (In the attachments.)
It's also important to note that while it does adopt the CSS Box-model, it is not a Cascading layout.
That's all I had to show. Essentially, right now Its a Kotlin -backed creation, but can be made for Java specifically, C++, C#, etc. I'm planning on adding more into the language to make it even more robust. What's more, it doesn't need to be OpenGL backed- it can use Java paint classes, SFML, etc etc. I just need to standardize the API for it. I guess what I'm wondering is, if I put it out there- would anyone want to use it for desktop application dev?
P.S. Of course the syntax is subject to change, via suggestion.
P.S.[2] The image in the middle of the editor is static, but wont be when I put 3D scenes in the scene-view.

• By janek29
Hi, I want to present my game called "246! Fast counter" - an engaging mathematical challenge! Add quickly and train your brain!

Use math and sum up numbers to get the right result. The correct result gives you more time for further mamtematic operations. Do not let the numbers fill all the free fields, because it will be the end of your adventure with math.

Act and add numbers quickly to get the right amount. Look for numbers in the borders and use them for adding - this will allow You to unlock more fields and get even more time. Collect as much as possible points - be simply the master of summation and the hero of mathematics!

Train brain every day to be even better in mathematics.

It is FREE!