Related
I was wondering how catch block works.
I have below code,
catch(ArithmeticException e){
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed");
}
catch(Exception e){
System.out.println("common task completed");
}
If divide by zero occurs it will go to Arithmetic Exception and skips rest.
How is it internally implemented so that it is going into the correct catch block?
If by "implemented" you mean "what is the bytecode generated for this", that part is of course covered by the language specification, and there is a good article about it.
Basically, every code segment (method) can have an associated exception table. In this table, you have an entry for every catch block, that specifies which lines of code are covered by it (the extent of the try block), what exception is being caught, and where to jump to handle it (the catch block).
When an exception is raised, the JVM goes through this table from top to bottom and continues execution in the first catch block that matches.
If it does not find one, it exits the current method and looks in the exception table of the caller (the exception bubbles up the call stack until someone deals with it).
It does not directly go to the matching catch block...
But it linearly searches each catch block to find the required exception, if it finds then it skips rest of the catch block... Thats All.
The first matching catch block is executed.
For more details see here: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
Its not much of going to a specific block. In your try block an exception can and normally is "thrown" your catch block merely anticipates the exception and "catches" it preventing the program from crashing.
` Java has a built-in mechanism for handling runtime errors, referred to as exception handling. This is to ensure that you can write robust programs for mission-critical applications.
Older programming languages such as C have some drawbacks in exception handing. For example, suppose the programmer wishes to open a file for processing:
1.The programmers are not made to aware of the exceptional conditions. For example, the file to be opened may not necessarily exist. The programmer therefore did not write codes to test whether the file exists before opening the file.
2.Suppose the programmer is aware of the exceptional conditions, he/she might decide to finish the main logic first, and write the exception handling codes later – this "later", unfortunately, usually never happens. In other words, you are not force to write the exception handling codes together with the main logic.
3.Suppose the programmer decided to write the exception handling codes, the exception handling codes intertwine with the main logic in many if-else statements. This makes main logic hard to follow and the entire program hard to read. For example,
if (file exists)
{
open file;
while (there is more records to be processed) {
if (no IO errors) {
process the file record
} else {
handle the errors
}
}
if (file is opened) close the file;
} else {``
report the file does not exist;
}
`
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have been coding in Java for work but everything I know about Java comes from googling how to do anything whenever I need to know. I have done C/C++ at school before and now I'm just getting into exception handling in Java.
In Java, why should we specify the exception type in the catch block? What are some advantages to doing so? What are some disadvantages to just using Exception instead of, say "IOException"?
Also when should I use the try/catch block when coding? I noticed that I got into the pattern of just coding the logic part, and I only add try/catch if an error shows while coding telling me to add it, or when I run the code and the program quits halfway because of an exception, then I find where it happens in the code and add the try/catch block there to "handle the exception" in order to get the code keep running. Is this how people normally decide where to add in try/catch? Is there a more efficient way such as "when doing certain things in code, add try/catch"?
Thanks a lot!
EDIT:
When should I use try/catch blocks and when should I use private void method() throws Exception? What's the difference between the two besides the syntax?
A lot of relatively new programmers have this thought that all exceptions are bad, but this isn't true. Exceptions are neither good or bad. They just provide information.
Take NullPointerExceptions vs FileNotFoundExceptions.
Generally (not always), if a NullPointerException is thrown, it means that there was a bug in your code somewhere. You forgot to initialize a variable, didnt check to see if a flag was true, etc. When these exceptions are thrown, you generally want your program to fail and crash, because it encountered unexpected behavior. You want the failure to be loud and obvious, because if the program didn't fail immediately after a null pointer, the program might get really wacky, and you would have a hard time finding the problem.
However, FileNotFoundExceptions are generally the opposite.
Imagine if at some point in your program, you prompted the user for a file. The user may or may not input a valid file, but the program shouldn't crash here either way. Instead, the user should be notified if the file can't be found, and prompted again. This is generally why you have catch blocks, so if that exception gets thrown, you can handle it and continue (by displaying your dialog/message/whatever).
However, if a NullPointerException was thrown here, you would definetly want your program to crash (as it's probably a bug in your code). This is why catch blocks force you to specify the Exception, so you can deal with some (such as FileNotFoundException), and let others through (such as NullPointerException)
Generally, you want to catch exceptions if your program is capable of recovering from that exception. This is (supposed to be) why java forces you to try/catch certain exceptions. Most of those exceptions are meant to be exceptions your program should be able to recover from (although sometimes, you would want to fail instead, either by declaring that your method throws that exception, or wrapping the caught exception in a RuntimeException).
I might be leaving out details I am unfamiliar with myself. But as far as I know specifying the specific exception type, allows you to get more detailed info on the error in the log.
Also eclipse and other ide's usually show a warning when it's "proper" to use try/catch blocks.
Hope it answers the question to some extent
The point of specifying which exceptions to catch is fairly straight forward. The main thing to remember is that Exceptions are classes, and have an inheritence hierarchy. For example, IOException inherits from Exception. This allows you to catch different exceptions, and handle them in different ways.
try {
....
} catch (IOException e){
logger.fatal("An IO Exception occurred.");
} catch (NullPointerException e){
logger.info("A null pointer exception occurred.");
}
In the above example, an IO exception will be logged as fatal, but a null pointer is only logged at the info level. Any exceptions that may be thrown besides these two will not be caught, and will be thrown to the next level of error handling. This could either crash your program, or a method higher up the call chain may handle the thrown exception.
try {
....
} catch (IOException e){
logger.fatal("An IO Exception occurred.");
} catch (NullPointerException e){
logger.info("A null pointer exception occurred.");
} catch (Exception e) {
logger.fatal("An unexpected exception occurred.");
}
In this second example, all exceptions are caught. Only one catch block will be executed though (The first one that matches).
A good way to plan when writing code is to:
1) Determine if this line of code can fail. (IO, parsing text, calling a service...).
2) If this code fails, do I want to handle this failure here (with a catch block) or later, by throwing the exception up the call chain.
You should specify the type of the exception in most cases because methods you call may throw different types of exceptions. For example, let's say you're trying to access a file in the file system, when you call the method to do this, the method can throw a FileNotFoundException which as the name describes, you will get when the file path you gave it does not exist. The method could also throw an IOException if the file does exist, but there's some other problem with the IO device or the file itself.
Usually, you would want to know the difference between these two errors and act accordingly, in which case you will have to put two catches, one for FileNotFoundException and another for IOException.
If for some reason you don't care about the specific error, then you simply put one catch for a regular Exception.
For the answers to your other questions, you can find them here http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html
so my professor has assigned us a project where we have to take in commands from a text file and use them to drive the flow of our program. These commands such as- Takeoff, land, load cargo, unload cargo, etc.- are meant to simulate an airplane-like object.
Sometimes these commands don't make sense to execute, like loading cargo while a plane is in-flight. Therefore, to prevent something like that from happening we had to code in our own exception classes i.e. "If the plane is ordered to load cargo while in flight, throw InvalidActionException"
My question is: how can I continue to read-in commands from the text file after exceptions have been thrown (seeing as how once they are thrown, the program cannot progress further
Here's an outline of what I want to do:
Scanner input = new Scanner(new FileInputStream("stuff1.txt"));
while(input.hasNextLine())
{
try
{
//execute commands by reading them using input.nextLine()
}
catch()
{
//catch any exceptions and ignore them... continue to read
//the file for more commands
}
}
I would appreciate any help. Thanks.
Catch appropriate exception and flow will automatically reach while loop condition.
After cathing exception nothing extra to be done to continue the program.
seeing as how once they are thrown, the program ends abruptly
Only uncaught exception stop a thread. I suggest you catch all the exceptions you want to continue after and you won't have a problem.
Catch your specific exception:
while(input.hasNextLine())
{
try
{
//execute commands by reading them using input.nextLine()
}
catch ( UserDefinedException ex )
{
//catch the exceptions you're throwing
}
}
That's exactly what you want to do. All the reading and processing statements go in the try block, and the catch block just contains error processing (which may consist of nothing other than printing a warning message somewhere.
The thing you need to be careful of is that you don't get stuck in an endless loop. Make sure each time around the loop you're processing new data!
Since your catch is inside the while loop, the loop will naturally continue onto the next iteration after the exception has been caught.
Any exception caught in your catch block(s) will not cause the program to terminate. Simply catch the Exception(s) you want handled and your loop will continue.
while(input.hasNextLine())
try {
//execute commands by reading them using input.nextLine()
}
catch (CargoLoadingException e)
{
System.err.println("Can't load cargo while the plane is in flight.");
}
catch (OtherException e)
{
e.printStackTrace();
}
}
Note that if you catch Throwable, you basically catch any exception that can be thrown. However, you probably only want to catch specific exceptions. For example, PlaneCrashException probably should cause the program to terminate.
The outline you have shown is sufficient to achieve what you want (i.e. the try-catch-construct is inside the while loop). Just make sure that the catch statement declares the correct type or supertype of exception you want to catch-and-ignore.
UPDATE: If you are unsure about what kind of exception to catch, you might want to catch "Throwable", but this is not really recommended. When your teacher had you implement your own exceptions, you probably based them off one existing Exception class. You might want to catch that Exception type then.
And on a totally differnt note, you might want to read in the entirety of the commands from the text file into a list of strings before executing the sequence. This might save you from some IO problems, because you keep the file handle open all the time (which seems unnecessary for such a straight-forward task).
To add to the other answers: Exceptions can do a number of jobs. All too commonly, they tell you that your program is hopelessly unstable and should shut down immediately.
Normally, they tell you that something bad and unexpected happened, and give you a chance to explain the problem to the user and then carry on. For instance, an unexpected End-Of-File exception. You can tell the user the file is bad and let them try another one. You can also print out a stack trace so they can call you and you can figure out what happened even if you did not print an extensive error message.
Note the split personality of this exception. Like the first type (RunTimeException instances, usually), they let you know exactly what happened almost without you doing anything. However, Java also forced you to be aware that an IOException could be thrown and tried to force you to write a nice message for the user. I've always been a bit puzzled about this. If I catch an EOFException, I know where it happened and I don't need the stack trace. (Of course, if I know an EOF cannot happen, I'm not going to bother with a proper message to the user, and the stack trace when it does happen will be very handy.)
But there's a third sort of an exception, sort of the second personality of the previous exception. It just lets you know something perfectly normal happened. It is highly efficient (if you set it up right; see below). And it can be a lot cleaner than returning values up a stack of method calls. It allows a method that already returns, say, a String (with a null reference being perfectly okay) to alert the calling method to a special condition and, optionally, provide vast amounts of data on that condition.
public static class MyEOFException extends EOFException {
// Saves creating a meaningless stack trace.
public Throwable fillInStackTrace() { return this; }
}
// Saves creating a new object every time you use it
public static MyEOFException myEOF = new MyEOFException();
Then, inside a method:
try {
for (;;) {
String text = readAStringFromFile( in );
// Do something with text...
}
}
catch (MyEOFException e) {
// Nothing at all needs to be done here.
// Note that MyEOFException COULD have beeen set up with tons of data and
// then a lot of work could be done. (The file might end with binary
// data, for instance, which would be in "e".)
}
The exception could be thrown many levels down and it will pop you out of the loop quite neatly. In most such cases, this would be a little too simplistic. Often it's too complicated; try-catch blocks can be annoying. Something like:
while (readAStringFromFile( in ));
is a lot nicer and faster to write if readAStringFromFile has a place to put what it read.
In your particular case, using exeptions like this may be what your professor is looking for. My personal experience is that there is almost always a better way to do it than with try-catch blocks, but when they do work they work really well.
There are 3 permutations of a try...catch...finally block in java.
try...catch
try...catch...finally
try...finally
Once the finally block is executed, control goes to the next line after the finally block. If I remove the finally block and move all its statements to the line after the try...catch block, would that have the same effect as having them in the finally block?
I know this is a very old question but I came across today and I was confused by the answers given. I mean, they are all correct but all answer on a theoretical or even philosophical level when there is a very straightforward practical answer to this question.
If you put a return, break, continue or any other java keyword that changes the sequential execution of code inside the catch block (or even try block), the statements inside the finally block will still be executed.
For example:
public void myFunc() {
double p = 1.0D;
String str = "bla";
try{
p = Double.valueOf(str);
}
catch(Exception ex){
System.out.println("Exception Happened");
return; //return statement here!!!
}finally{
System.out.println("Finally");
}
System.out.println("After finally");
}
when executed this code will print:
Exception Happened
Finally
That is the most important reason for the existence of a finally block. Most answers imply it or refer to it on the sidelines but none of them is putting emphasis on it. I think because this is kind of a newbie question such a straightforward answer is very important.
I think willcode comes the closest to expressing the key point here, and probably everyone means it but are not clear.
The problem is there is indeed something very wrong with what you are asking: "If i write all the statements after catch block instead of writing them into finally block then then would there be anything wrong?"
If you write all the statements after the catch block, what you are implying is that
1) You will always catch the exception.
2) You will always continue on to the next statements after you catch the exception.
This implies that you will always continue the execution "normally" after an exception, which is generally something you never in fact want to do.
Exceptions should be just that - exceptional. If you can in fact handle an exception, it is always better to write your code to consider those conditions first and not lead to an exception at all. If you follow this model then exceptions are truly exceptional - conditions you could not anticipate or at most not fix. Really not anticipate is what you should work towards. This means in general you are unable to handle true exceptions, which also means you should not just continue execution, often you end the application instead.
What is normally done is you allow an error to propagate back up the call stack. Some say this is done on the off chance that someone higher up in the chain may be able to handle it. I would say that essentially never happens, there are two real purposes to do this. One it may be something the user can fix, if there is one. So you propagate the error back up until you get to where you can report it to the user. Or two, a user cannot fix it but you want to get the entire call stack for debugging. Then you catch it at the top to fail gracefully.
The finally block now should have more meaning to you. As everyone says it always runs. The clearest use of a finally is really in a try... finally block. What you are now saying is if the code runs fine, great. We still need to do some clean up and the finally always executes then we move on. But if an exception occurs, we now really need that finally block because we may still need to do some clean up, but we are no longer catching the exception here so we are not going to be moving on anymore. The finally block is essential to ensure that clean up occurs.
The idea of an exception always halting execution may be hard for someone to grasp until they have a certain amount of experience, but that is in fact the way to always do things. If an error happened, either it was so minor you should have accounted for it to begin with, or else there are just more and more errors waiting to happen down the line.
"Swallowing" errors - catching them and moving on is the worst thing you can do because your program becomes unpredictable and you cannot find and fix bugs.
Well written code will contain as many try ... finally blocks as are necessary to make sure that resources are always released no matter the outcome. But well written code generally contain only a small number of try ... catch blocks that exist primarily to allow an application to fail as gracefully as possible, or defer to the user, which means at least always pass a message to the user etc. But you usually do not just catch an error and keep going.
The highlight is that a finally block is guaranteed to be executed even if an exception is raised and not caught. You then use the finally block, as a one time chance, to perform necessary clean-up like closing streams. The code after the finally block might never be reached.
From the java tutorial
The finally block always executes when
the try block exits. This ensures that
the finally block is executed even if
an unexpected exception occurs. But
finally is useful for more than just
exception handling — it allows the
programmer to avoid having cleanup
code accidentally bypassed by a
return, continue, or break. Putting
cleanup code in a finally block is
always a good practice, even when no
exceptions are anticipated.
If I understand the question, you're asking what's the difference between:
try {
Foo f = new Foo();
f.bar();
}
finally
{
Foo.baz();
}
And:
// This doesn't actually compile because a try block needs a catch and/or finally block
try {
Foo f = new Foo();
f.bar();
}
Foo.baz();
Or, more likely:
Foo f = new Foo();
f.bar();
Foo.baz();
The difference is that if either new Foo() or f.bar() throw an exception, the finally block will get executed in the first case, but that Foo.baz() won't get executed in the last two cases: instead control will skip over Foo.baz() while the JVM looks for an exception handler.
EDIT
Responding to your comment, what about:
Foo f = new Foo();
try {
f.bar();
}
catch (Exception ex)
{
// ...
}
f.baz();
You are right that, assuming the catch block doesn't rethrow the exception, or return from the method indicating a failure occured, then f.baz() gets called regardless of whether there was an exception. Even in that case, however, the finally block serves as documentation that f.baz() is used for cleanup.
More importantly, the fact that an exception was thrown usually is important, so it's very hard to write code that continues on doing whatever it was doing without knowing that an exception was thrown. There are times that exceptions indicate silly things that you can ignore, and in that case you should swallow the exception. More often, however, you will want to signal failure, either by rethrowing the exception (or throwing a different exception) or returning from the method with an error code.
For example, if f.bar() is supposed to convert a String to a Double, and on failure it throws a NumberFormatException, then code after the try block probably needs to know that the String was not actually converted to a Double. And, so, in general you won't want to continue after the catch block. Instead, you'll want to signal failure. This is known as "abort on failure" (compared to "resume on failure," which probably should be called "muddle on after failure with your fingers crossed").
Except, in special cases you may be able to muddle on. For instance, the catch block could set the relevant Double to Double.NaN which is designed specifically to propagate errors correctly in math expressions. Even in that case, the finally block serves as documentation that f.baz() is involved in some kind of cleanup.
The finally block contains lines of code that should be executed regardless whether an exception has been caught or not. Even if you decide to stop code running in that method. So code after the t-c-f might not be executed, but the finally code is "guaranteed" (guaranteed in the sense of a non crashing immediately breaking non handleable error).
Yes, there would be something very critically wrong.
And that is, your code would only run if there is an error.
Statements inside finally always run, regardless of an exception being thrown. That is the point.
finally block especially used at the time of exception prevention. If any runtime error occurs, the program may lead to terminate. So at this time, it will call finally block before going to terminate the program. Usually 'finally' contains connection closing statements, save operations and file input, output close operations.
If your code never throws exception, or you are consuming all exception that will be correct. That is not what always happens.
The question was indeed answered here (how to use finally)
My understanding of the answer is: there would be circumstances in which we would throw some exception that the except block won't be able to handle. What do you do in that situation? You wanna move on? Not a great idea! You better print something that indicates that you passed through a stage where an exception may or may not have occurred, if the exception occurred it should have been handled by the catch statement and if it was not handled, there may be some unmatched exception
There are certain predefined exceptions in Java, which, if thrown, report that something serious has happened and you'd better improve your code, than catching them in a catch block (if I have understood it correctly). But still I find many programs in which I have the following:
} catch (IOException e) {
...
} catch (FileNotFoundException e) {
....
}
and I thought that IOException and FileNotFoundException are exactly such kind of exceptions, which we shouldn't catch in a catch block. Why people do this? Is it better to catch them like this? Java compiler warns anyway about any problem of that kind.
Thank you.
No, there's nothing wrong with catching IOException and FileNotFoundException - if you can genuinely handle those exceptions. That's the important bit - can you really proceed in the face of that exception? Sometimes you can - very often at the top level of a server, for example, where just because one request fails doesn't mean the next can't proceed. Less often in client apps, although it very much depends on the situation. Can't read a file when you're trying to do a batch import? Okay, abort the operation but don't necessarily shut down the whole process...
You shouldn't have them that way round, admittedly - the FileNotFoundException would be masked by the IOException which it derives from. Fortunately the compiler flat-out prevents you from doing this.
The order that you show, with IOException caught before FileNotFoundException is wrong. Since FileNotFoundException extends IOException, when a FileNotFoundException is thrown, the first handler will be used, and the second handler is dead code.
I haven't tried it, but I'm a little surprised if this compiles. A static analysis tool like FindBugs would catch this error, I hope.
As far as whether you should catch a FileNotFoundException, it depends on the caller. However, I will say that a FileNotFoundException can often be recovered in a meaningful way—prompting for another file, trying a fallback location—rather than simply logging the error or aborting the process.
There are two types of exceptions in Java, checked exceptions and unchecked exceptions.
Checked exceptions must be handled in a catch block. Not doing this will cause a compiler error. IOException is an example of a checked exception, and must be handled. What you actually do here depends on the application in question, but the Exception must be handled to keep the compiler happy.
Unchecked exceptions do not need to be caught. All classes that extend from RuntimeException are unchecked. A good example of this is a NullPointerException or an ArrayIndexOutOfBoundsException. The compiler doesn't force you to catch these exceptions, but they may still occur when your program runs, causing it to crash.
For the record, IOException can be thrown for something as simple as trying to open a file that doesn't exist. It is a good idea to handle something like this and recover gracefully (dialog to the user saying the file doesn't exist and make an open file dialog reappear or something), rather than letting the program crash.
The do this in order to handle different types of exceptions differently.
Typically you are going to want to catch the most granular exceptions first, if you put the more broad exceptions at the beginning of your catch block, you will execute that code first, then hit the finally block.
Jon is right, the catch that catches the IOException will catch all IOExceptions and any sub-type of IOException, and since FileNotFoundException is a type of IOException, it will never hit the 2nd catch.
As Jon says, catching these exceptions is fine in many cases. The kind of exceptions that you shouldn't be catching are things like NullPointerException and ArrayIndexOutOfBoundsException, these indicate bugs in your code.
Java has two types of exception: checked exceptions and unchecked exceptions (those that inherit from RuntimeException).
Checked exceptions, such as IOException, are usually used for unpredictable scenarios that can't be avoided by writing better code. The fact that they are checked means that the compiler forces you to write code that accounts for the possibility of the exceptional scenario. For example, you have to consider the possibility of a FileNotFoundException because you can't guarantee that the file will exist (somebody might move it while your program is running). An IOException might occur because a network connection gets dropped. The compiler forces you to provide a strategy for dealing with these cases, even if it's just to pass the buck by allowing the exception to propagate up the stack for calling code to handle.
Unchecked exceptions on the other hand are best used for things that can be avoided by changing the code. A NullPointerException can always be avoided if the code makes a check for the possibility of a null reference. Likewise, if you are careful with your indices, you will never get an ArrayIndexOutOfBoundsException. The compiler doesn't oblige you to handle these scenarios since they represent bugs that should be fixed.
I thought that IOException and FileNotFoundException are exactly such kind of exceptions
Nope, those are actually the "other" type of exceptions, the kind that go beyond your programming skills. No matter how good do you program, the compiler and the libraries make you be "conscious" that something might happen.
Think about this scenario:
You create an application that saves data to a temp folder.
Everything is alright, you have checked the folder exists, and if not, you create it your self.
And then you're writing 2 mb to that temp folder.
Suddenly, other system process, deletes your temp folder, and you cannot write anymore.
There is nothing you can do to prevent this programmatically, in some systems that operation could happen ( In unix the root user may perform rm -rf /tmp and there is nothing you can do about it. In windows I think the system won't let other process delete a file is is being used )
By forcing you to check this kind of exceptions in the code, the platform designers thought that at least you're aware of this.
Jon is correct sometimes there is nothing you can do about it, probably logging before the program dies, that is considered as "handle the exception" ( poor handle yes, but handle at least )
try {
....
} catch( IOException ioe ) {
logger.severe(
String.format("Got ioe while writting file %s. Data was acquired using id = %d, the message is: %s",
fileName,
idWhereDataCame,
ioe.getMessage()) );
throw ioe;
}
Another thing you can do is to "chain" the exception to fit the abstraction.
Probably your application, is has a GUI, showing a IOException to the user won't mean anything or could be a security vulnerability. A modified message could be sent.
try {
....
} catch( IOException ioe ) {
throw new EndUserException("The operation you've requeste could not be completed, please contact your administrator" , ioe );
}
And the EndUserException could be trapped somewhere in the gui and presented to the user in a Dialog message ( instead of just disappearing the app in his eyes without further information ). Of course there was nothing you can do to recover that IOException, but at least you die with style :P
Finally a client code, could use different implementations, and not all the exceptions would make sense.
For instance, think again on the fist scenario. That same "operation" could have three kinds of "plugins" services to perform the data saving.
a) Write the data to a file.
b) Or, write to a db
c) Or write to a remote server.
The interface should not throw:
java.io.IOException
java.sql.SQLException
nor
java.net.UnknownHostException
But instead something like
my.application.DataNotSavedException
and the different implementations would handle the exception at the correct level, and transform it to the appropriate abstraction:
Client code:
DataSaver saver = DataServer.getSaverFor("someKeyIdString");
try {
saver.save( myData );
} catch( DataNotSavedException dnse ) {
// Oh well... .
ShowEndUserError("Data could not be saved due to : " dnse.getMessage() );
}
Implementation code:
class ServerSaver implements DataSaver {
....
public void save( Data data ) throws DataNotSavedException {
// Connect the remore server.
try {
Socket socket = new Socket( this.remoteServer, this.remotePort );
OuputStream out = socket.getOut....
....
....
} catch ( UnknownHostException uhe ) {
// Oops....
throw new DataNotSavedException( uhe );
}
}
}
FileSaver and DatabaseSaver would do something similar.
All of these are Checked Exceptions because the compiler make you check them.
When to use one or the other ( checked / unchecked): here
There are other two kinds: here
And finally a much simpler explanation of the Runtime is: here
To take this idea sideways a bit: maybe in another domain it is clearer
What do you do if the car in front of you stops suddenly.
Stop!
So we handle the exception.
So back to code:
What do you do if the file you need is not available ?
either
Have a backup. Compiled in as a
resource because it's part of your
program. I'm not kidding.
IFF It's a user supplied file :Tell the user; it's their file.
Abort the program with a message to the user because your software SYSTEM is
broken.
It is my opinion that there is no fourth option.
Our C#/VC++ brethren choose unchecked exceptions. Many "experts" think checked exceptions are bad: my contention is that life is difficult, get over it.
Checked exceptions represent known failure modes: and have to be addressed.
Your fishbone diagram has a straight lie for normal operation and branches off the side for failures. Checked exceptions are the anticipated failures.
Now, once you start handling Runtime exceptions, then it gets interesting.
A Java program can run mostly normally with functions that do not work.
By this, I mean they throw null pointer exceptions, array bounds errors, invalid arguments, and run out of heap space. This makes incremental delivery quite feasible.
(If you ever do catch Runtime errors, log them. Otherwise you never know to fix things)