try catch finally understanding check - java

I've found this subject very confusing was wondering if i could get some feedback to see if I understand this concept.
if you do something like
int x = "this is not an int"
java will complain and throw a crash error when you try to run it, in this case "static error". so if
I wanted to create a exception handler for this it would be something like this?
try
{
int x = "this is not an int"
}catch(Staticerror nameIcanMakeUp){
x = 4}
finally{
does the x has to be set to a acceptable value in the catch to prevent a crash?
does the first argument of catch have to be the same as what java would say when it crashes?
do I put the rest of the code in the finally block should I have more code after the bit of code that might throw exceptions?
also how would I do this with a exception I want to define like if its an age field and I don't want people entering dates from the future etc?

if you do something like int x = "this is not an int" java will complain
Java is a statically typed language so it picks up these error at compile time, not when you run the program.
and throw a crash error when you try to run it,
Actually the javac compiler gives you the error.
I wanted to create a exception handler for this it would be something like this?
There is no way to ignore code which doesn't compile at runtime as you can't run a program which didn't compile.
What you can do is something like this.
Object o = "This is not an Integer";
Integer i = (Integer) o;
This does compile and produces a runtime rather than a compile time error. You can catch this with
Object o = "This is not an Integer";
try {
Integer i = (Integer) o;
} catch(ClassCastException cce) {
cce.printStackTrace();
}
does the x has to be set to a acceptable value in the catch to prevent a crash?
The code in the catch block also has to compile and run without throwing an Exception.
does the first argument of catch have to be the same as what java would say when it crashes?
The class you try to catch has to be the class of the exception or a super class.
do I put the rest of the code in the finally block
It depends, but usually you don't need a finally block.
should I have more code after the bit of code that might throw exceptions?
It depends on what you are trying to do but usually you put as little in this block as possible.
also how would I do this with a exception I want to define like if its an age field and I don't want people entering dates from the future etc?
You can create you own custom Exception by extending an existing one, but I tend to re-use the existing ones like
if (age < 0)
throw new IllegalArgumentException("Age cannot be negative");

Related

Run a program without Try/Catch block

I'm making a sort of chat program in Java. Specifically, if I ask "can you open chrome?", the program will reply with "yes..." and then opens Google Chrome (Windows).
I have created the path to the Chrome as a string:
Runtime rt = Runtime.getRuntime()
String file="C:\\Program Files (x86)\\Google\\Chrome\\Application\\Chrome.exe";
I try to call the String, but says to either "Surround Statement with try/catch" or "Surround block with try/catch". Or the "Add throws clause to the "java.io.IOException" ".
myVocab.addPhrase("Can you open Chrome?", "Yes, one moment..." + rt.exec(file));
Whenever I do either of these, Chrome just opens automatically.
I'm somewhat new to Java so please tell me if there's an easier way to do this, or if I'm doing this completely wrong.
Some java functions need to be implemented with the try catch statements because it is possible to get an exception inside that function. An exception is defined as "An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions" more info
So, to manage an exception, for your case, you could:
try { code1 } catch (ExceptionType name) { code2 }
where ExceptionType should correspond to the possible error type your code1 could give you.
Ex:
try { //code to open google } catch (InterruptedException e) { e.printStackTrace(); }
e.printStackTrace(); will print error details

Exception - why even bother throwing?

So, I know this is going to sound a little extreme but I'm trying to make a point:
OK. so my code doesn't care what kind of exception is being thrown, 99.9% of the time if an exception is being thrown it handles it the same no matter what.
Now, Why should i even bother throwing \ creating new exception in my code?
apparently all the libraries i use throw them already and the are very informative as well.
a null object passed for my method? who cares, a null pointer exception will be thrown automatically for me.
Can you make a good argument why should i create new exceptions and throw them?
EDIT what i mean:
why bother with this:
public myMethod() {
try {
doStuff1();
}
catch(Exception e) {
throw new Exception("Error in doStuff1");
}
try {
doStuff2();
}
catch(Exception e) {
throw new Exception("Error in doStuff2");
}
when i can use this:
public myMethod() {
doStuff1();
doStuff2();
}
Your client wants detailed error reporting. What went wrong, and where did it go wrong.
They don't have a clue what a null pointer exception is. And even then, that in itself is not particularly helpful without the stack trace. So a null pointer gets passed into your RetrieveReportX method? Check if it's null and throw a ReportXNoIdentifierException rather than letting it auto-throw a null pointer exception. Then you'll have a error handler somewhere that, based on these custom exceptions, can report exactly what went wrong in what (human) process, and your client is happy because rather than NullPointerException at [stacktrace], they can see "An identifier was not supplied when attempting to retrieve report X."
why should i create new exceptions and throw them?
In some cases it is common and good practice to throw Exception deliberately.
Take
IllegalArgumentException
If your method only accepts arguments within a particular range, e.g. only positive numbers, then you should check for invalid parameters and throw an IllegalArgumentException.
For example:
public int calculateFactorial(int n) {
if (n < 0)
throw new IllegalArgumentException("n must be positive");
if (n >= 60)
throw new IllegalArgumentException("n must be < 60");
...
}
public void findFactorial(int n)
{
try{
calculateFactorial(n)
}catch(IllegalArgumentException ie){
System.out.println(ie.getMessage());
}
}
From Java tutorials - Advantages of Exceptions
Advantage 1: Separating Error-Handling Code from "Regular" Code
Advantage 2: Propagating Errors Up the Call Stack
Advantage 3: Grouping and Differentiating Error Types
Answer
Exception handlers that are too general can make code more error-prone by catching and handling exceptions that weren't anticipated by the programmer and for which the handler was not intended.
As noted, you can create groups of exceptions and handle exceptions in a general fashion, or you can use the specific exception type to differentiate exceptions and handle exceptions in an exact fashion.

Using try-catch -- Skipping try

I'm trying to write a code that I can try a JSON object and if it's the wrong format inform the user somehow.
The code is :
public boolean sjekkSporingsNummer (JSONObject object){ //object is passed correct
Boolean riktigSporing = null;
riktigSporing = true; //riktig sporing is set to true
//if its true the json is correct
try {
JSONArray consignmentSet = object.getJSONArray("consignmentSet");
JSONObject object1 = consignmentSet.getJSONObject(0);
riktigSporing = true;
}catch (Exception e){ //skips straigt to here
e.printStackTrace();
riktigSporing = false;
}
return riktigSporing;
After if failes with :
07-31 12:34:07.243 15479-15479/com.example.posten E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
What seems wierd to me is that my app skips the try and goes straight to the return statement.
I would like it to try and of it failes set "riktigSporing" to false.
What am I doing wrong?
I bet it doesn't. I suspect your input parameter is null and you trigger an NPE very early.
Note also you could possibly unbox a null into a primitive boolean, and that won't work.
EDIT:
FATAL EXCEPTION: main
java.lang.NullPointerException
suggests this further. You should have a corresponding line number in your stacktrace.
Most probably you get an exception at the first line in the try block.
I think there is a better approach to code this method. Do not use boolean to show how successful was this method execution. If this method executes ok, then return nothing. But if there's an error upon execution, throw an exception specific to the error you have got.
Avoid use of general exception classes where possible. Use exception classes specific to a sitiation which caused the problem. I.e NullPointerException, JSONException, NumberFormatException and so on. If there's a custom specific possible reason or reasons for exceptions then make your custom exception class and throw it when necessary to mark the problem as precise as possible.
It will let the caller process this error properly or throw this exception further.
In general this approach makes your application more consistent and manageable.
You need to set your boolean in this catch:
catch (JSONException e) {
e.printStackTrace();
riktigSporing = false;
}
In the case of some error with JSON this catch will be called, not second one. I think in your scenario your second catch is not required.
If you want to use generally Exception, remove JSONException and let there only Exception
Note: When i looked at your snippet of code, i suggest you to use boolean as primitive data-type instead of Boolean. It will be more clear and efficient.
It is impossible. I think try block is executed without a exception thrown and thus it must go to return statement. Or else your code might not have build properly.

Exceptions in Java

At the moment I am developing a website while using the Playframework2. I am just a beginner in programming. I read some books about exceptions but now in the real world , exception handling is really strange.
To be honest I don't really care what exceptions are thrown I handle all exceptions the same way.
return badrequest(); . I only use exceptions for logging.
try{
...
}
catch(Exeption e){
//log
return badrequest();
}
But this is so much boilerplate and it's really annoying to write, because every method throws the same exceptions.
Any tips , hints or resources that you could give me?
edit:
An example would be my "global" config file. Because I need to connect to the db every time I thought i could write a singleton for this problem.
private Datastore connect() throws UnknownHostException, MongoException,
DbAuthException {
Mongo m = new Mongo(dbUrl, dbPort);
Datastore ds = new Morphia().createDatastore(m, dbName);
boolean con = ds.getDB().authenticate(username, password.toCharArray());
if (!con)
throw new DbAuthException();
return ds;
}
This also results in a try and catch every time I want to connect to the db. My problem is I don't think I can handle them diffidently.
A code example :
public static Result addComment(String title) {
try {
Datastore ds = DatabaseConnect.getInstance().getDatastore();
Form<Comment> filledForm = commentForm.bindFromRequest();
Comment userComment = filledForm.get();
userComment.setUsername(Util.getUsernameFromSession(ctx()));
User.increasePointsBy(ctx(), 1);
UserGuides.addComment(title, userComment);
} catch (Exception e) {
return badRequest();
}
return redirect(routes.Guides.blank());
}
In this case I was to lazy to write the same try and catch over and over again, and this is duplicated code.
Maybe there is a book that explains how to design a big application with exception handling?
When you invoke a method, you do not necessarily have to catch the exceptions right there. You can let your callers handle them (declaring a throws clause if it is a checked exception). In fact, the ability to pass them on to the callers without any additional work is the distinguishing feature of exceptions.
My team has adopted the following coding standard: We throw checked exceptions for those rare cases when we want to recover from a failure, and unchecked exceptions for anything else. There is only a single catch block for the unchecked exceptions in a method so high in the call stack that all requests pass through it (for instance in a ServletFilter). This catch block logs the exception, and forwards the user to the "Sorry, this shouldn't have happened" page.
Have you looked at your code to examine why you're throwing all these exceptions? Exceptions are there for a reason- to tell you that something went wrong. If you're writing too much "boilerplate" try-catch code and you're not in a thousand line application, you have to refactor.
try-catch can be irritating when you have a complex block and can become very monotonous and boilerplate (Marc Gravell even said he usually uses try-finally) but as a new programmer, it would be helpful for you to examine the code that you write and figure out how to either handle or avoid those exceptions.
As akf mentions, ignoring exceptions can also be hazardous to debugging. It will be harder to track down where something catastrophic went wrong if you're missing exceptions leading up to it.

How do I add state information without writing repetitive code when catching multiple Java exceptions?

I've read a few other posts like this one about avoiding repetition in Java catch blocks. Apparently, what I really want is "multi-catch", but seeing as Java 7 isn't here yet, is there a good pattern to let me add state to my exceptions, then re-throw them, without catching the kitchen sink?
Specifically, I have some code that makes library calls, which can throw exceptions, but don't provide nearly enough context for successful debuging. I find myself having a problem, then going in, wrapping the library call in a try/catch, catching the specific exception, then adding extra state information in the catch block and re-throwing the caught exception. I then re-iterate through that loop over and over, each time finding a new error condition to log. I wind up with
try {
make_library_call();
}
catch (SomeException e){
throw new SomeException ("Needed local state information is " + importantInfo, e);
}
catch (SomeOtherException e){
throw new SomeOtherException ("Needed local state information is " + importantInfo, e);
}
catch (YetAnotherException e){
throw new YetAnotherException ("Needed local state information is " + importantInfo, e);
}
etc etc. I think what I'd really like to see is more along the lines of
try {
make_lib_call();
}
catch(Exception e){
e.AddSomeInformationSomehow("Needed Info" + importantInfo);
throw e;
}
assuming that in that case e would keep its actual runtime type when re-thrown -- in this case, even catching unchecked would probably be OK since I'd be re-throwing them, and they'd benefit from carrying the extra state info as well. I guess an alternate might be something like
try{
make_lib_call();
}
finally {
if (/*an exception happened*/)
logger.debug("Some state info: " + importantInfo);
}
but I don't know how to write the conditional. Is that crazy / wrong?
You're probably expecting this, but no, there isn't a good (and by good I mean clean) way to do this. You're probably expecting it because you subconsciously knew that if there was a good pattern for doing this, it probably wouldn't have been worth adding to Java 7.
It's actually the final rethrow feature that you'd find really handy in this case.
For the alternative:
boolean isOk = false;
try{
make_lib_call();
isOk = true;
}
finally {
if (!isOk)
logger.debug("Some state info: " + importantInfo);
}

Categories