Hello, I'm new in Java programming, just learning it and I want to ask you about the Exceptions. As much as I understood, I just need to create a class e.g. "MyException" that extends the Exception class, and use the exception specification "throws" in the function that might throw the particular exception, and after that throw the exception inside the function. I also read about " try" and "catch ", but what I can't get clear in my mind is the following: Do I need to write in the class "MyException" that e.g. if something doesn't happen, only then throw the exception... or the compiler will know when to throw the exception... I really don't get it. If I don't want the user to be able to insert integers in the file, just String, do I specify this somewhere, or just write "try" and "catch(Exception e)" ?
An important thing to understand is that there are two types of exceptions:
- checked exceptions, which are thrown when your code (or some code in the Java libraries) explicitly throws them; in this case, methods that throw such exceptions must be declared as throwing them, and code that calls such methods is forced to deal with the exception in some way (either with a try/catch block, or by "throwing it up")
- unchecked exceptions are special exceptions, such as IndexOutOfBoundsException, NullPointerException that don't need to be explicitly handled (you've probably seen that if part of your code accidentally has a null pointer, the exception "automatically" gets printed out without you having to catch it) -- what happens here is that something called the "default uncaught exception handler" takes care of it
Now, there are certain language operations that can throw certain unchecked exceptions (such as trying to access a out-of-bounds array index, doing an integer division by zero, or accessing a null object reference). So in these cases, no you don't need to explicitly throw anything -- you kind of have no choice. (Though you can catch them and deal with them).
You also can explicitly throw any type of exception from any method that you write -- you don't have to create your own exception class if you don't want to. For example, if you want to signal to the caller of your method that they've passed in an invalid argument, then Java already defines IllegalArgumentException which you can use.
I don't know if it's helpful to you, but there's a Java exceptions tutorial on my web site that you might want to take a look at.
Thanks for the link, it is helpful. I understand that there are these so called "Runtime Exceptions", I'm not really interested in them. I will give you this kind of example so you would understand my question: Suppose that I want to read from a file, and I only wanna read the Strings. So, how do I handle the situation if a user insert an integer in the file ? Can I handle it with the exception handlers, or do I have to sysout - "Enter only Strings in the file..." ? Should I write some special code or the exception is handled with in some higher-level mechanisms...
OK, so in this specific example, absolutely any sequence of bytes can be a valid string. So when you read a string from the file-- I assume you're thinking of one "string" per line, so you'd generally use BufferedReader.readLine()-- Java can't predict that what you actually want is strings that fulfil a certain condition, e.g. strings that aren't also valid number representations. So in this specific case, you would have to specifically check for the strings not being integers, and "do something" in that case:
- if you throw an exception, you are generally (a) signalling to the PROGRAM that something has gone wrong, and (b) controlling error flow within your program -- generally terminating the "bit of program" that was running -- e.g. if you had a method that read the strings, you could make that method throw the exception;
- if you just print something out, this might be fine if you just want to warn the user of that particular failure, but it doesn't tell your program that something's gone wrong -- so unless you do something else, it'll just plough on regardless
Now, if you throw an ordinary checked exception, that means that you have to catch it somewhere. For example, the bit of program that calls your string-reading method could have a try/catch, and in the catch block, print out a message to the user. You might think, "why don't I just print the message when I detect the bad string", but the point is the exception allows you to control program flow: terminating the method, or possibly interrupting a whole chain of methods and passing the error "back up to the caller".
If the exception that you throw is some type of RuntimeException, then you don't have to catch it (though you can) -- if nothing catches it, then the thread (=your program -- I assume you're not doing multithreaded programming yet) will terminate, and Java's default exception handler will kick in, printing out the exception.
Now, on the other hand, there are cases where "the system" will automatically throw an exception:
- many library methods will throw exceptions in particular documented cases -- for example, file operations such as readLine() can throw IOException; if you were using Integer.parseInt() to turn a string into a number, it would throw NumberFormatException if the string wasn't a valid int; but that depends on the particular library call you're making and you need to check the documentation of the particular method in question
- as I mentioned in my previous post, there are a few "build-in" operations that can also throw (unchecked) exceptions: divide by zero, running out of memory, calling a method on a null object, trying to use a negative array index etc etc.
OK, thank you very much, I must say I got a really clearer picture of what's happening when throwing an exception. I will try to write a few classes, I hope there'll be no problems at all. Thanks again !
Neil... You have a fantatsic website. Well done!
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.