Types of Exception in Java - java

I am confused about types of exceptions in Java. On many tutorial websites I have seen that two types of exception are there in java
Compile time exception
Run time exception
But when I talked with some java masters, according to them there is no such thing like compile time exception. They said it was compile time errors not exception, as well as I found nothing about compile time exception in Java docs. But when I run following program
File f = new File("C:/Documents and Settings/satyajeet/Desktop/satya.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
System.out.println(s);
I got below output if try catch not provided.
D:\jdk1.6.0_19\bin>javac Testing.java
Testing.java:7: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
FileReader fr=new FileReader(f);
^
Testing.java:9: unreported exception java.io.IOException; must be caught or declared to be thrown
String s=br.readLine();
^
2 errors
So should I consider this Error or compile time exception?

There are 3 types of Throwables in Java.
Checked Exceptions (Exception and down the chain, save for RuntimeException). These are checked by the compiler and must be caught when thrown. They represent an exceptional condition that is usually recoverable, e.g. when a referenced file is not found on the file system (see FileNotFoundException).
Unchecked or runtime Exceptions (children of RuntimeException). These can be thrown without catching. They typically represent programming errors, for instance invoking methods on a null object (see NullPointerException).
Errors. These are unchecked as well. They are thrown by the JVM when something very wrong is happening, typically beyond the developer's direct control (e.g. out of memory, see OutOfMemoryError). Compiler errors are issued by the Java compiler when your code fails to compile, for various reason such as bad syntax, ambiguous calls, failing to catch a checked Exception, etc. etc.

Any "famous website" that said that should not be read. It is rubbish. There is no such thing as a "compile time exception". The Java Geeks you were talking to are correct1.
Actually, you probably misread or misunderstood what you read on those "famous sites". There are "compile time ERRORS" and "run time EXCEPTIONS".
In your example, what you have is a couple of compile time error message, that are due to errors in your code. The errors are there because your code does not handle exceptions correctly, but they are ERRORS nonetheless. And they are detected at compile time ... by the Java compiler.
1 ... and maybe it is time to stop using semi-derogatory labels like "geek" for them. It sounds like they deserve some respect.

There is no such thing as "compile-time exceptions". Exceptions only happen at runtime (and they can be checked or unchecked - you may want to look this up).
What you have there is simply a compilation error. Your code isn't even valid Java.
By the way, most tutorials are rubbish. Use reputable sources, like the Oracle tutorials. Or a good book.

Their are no compile time exceptions. As the above comments mentioned.
Please find below javdocs on exceptions and link to information on checked and unchecked exceptions.
https://docs.oracle.com/javase/tutorial/essential/exceptions/
http://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/
You also find the below discussion useful
Differences between Exception and Error

If you got this during compilation then these two are compilation errors. Compilation errors are basically problems reported by the java compiler. Compilation error may include:
Sytax error
Classpath related error
try-catch block related error (ones reported by you)
And if you got this while running the program, they are Exceptions. Java Exception, as defined in the doc, is an exceptional event which occurs during execution of a program, that disrupts the normal flow of the program

The output of javac.exe you posted is an error of a software different from the one you are developing.
It means that your code does not complains to the Java Code paradigms: in fact, you are not checking a checked exception.
Your code has not thrown any Exception or Error, it simply does not exist.

There are the two type of exception in java.
Checked Exception
Unchecked Exception
Checked : exception must be handled by programmer otherwise the program would throws the compilation error.
"so you can called checked exception is compile time exception"
Now Unchecked Exception : In the unchecked exception programmer can write the code in such a way to avoid the unchecked exception. Programmer can not get the compilation exception.
"You can called unchecked exception is a runtime exception"
List of Checked Exception:
ClassNotFoundException
EOFException
IllegalAccessException...etc
if method should throwing a checked exception then it should be handled by the
try{}catch(Exception ex ){} Or you can use the throws keyword.
List of Unchecked Exception
ArithmeticException
NullPointerException
ArrayIndexOutOfBound...etc

Related

Java Exception generates compiler error, but replacing type of exception does not generate a compiler error [duplicate]

Joshua Bloch in "Effective Java" said that
Use checked exceptions for
recoverable conditions and runtime
exceptions for programming errors
(Item 58 in 2nd edition)
Let's see if I understand this correctly.
Here is my understanding of a checked exception:
try{
String userInput = //read in user input
Long id = Long.parseLong(userInput);
}catch(NumberFormatException e){
id = 0; //recover the situation by setting the id to 0
}
1. Is the above considered a checked exception?
2. Is RuntimeException an unchecked exception?
Here is my understanding of an unchecked exception:
try{
File file = new File("my/file/path");
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//3. What should I do here?
//Should I "throw new FileNotFoundException("File not found");"?
//Should I log?
//Or should I System.exit(0);?
}
4. Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I? (Note: my 3rd question is inside the catch above)
try{
String filePath = //read in from user input file path
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//Kindly prompt the user an error message
//Somehow ask the user to re-enter the file path.
}
5. Why do people do this?
public void someMethod throws Exception{
}
Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up?
6. Should I bubble up the exact exception or mask it using Exception?
Below are my readings
In Java, when should I create a checked exception, and when should it be a runtime exception?
When to choose checked and unchecked exceptions
Many people say that checked exceptions (i.e. these that you should explicitly catch or rethrow) should not be used at all. They were eliminated in C# for example, and most languages don't have them. So you can always throw a subclass of RuntimeException (unchecked exception)
However, I think checked exceptions are useful - they are used when you want to force the user of your API to think how to handle the exceptional situation (if it is recoverable). It's just that checked exceptions are overused in the Java platform, which makes people hate them.
Here's my extended view on the topic.
As for the particular questions:
Is the NumberFormatException consider a checked exception?
No. NumberFormatException is unchecked (= is subclass of RuntimeException). Why? I don't know. (but there should have been a method isValidInteger(..))
Is RuntimeException an unchecked exception?
Yes, exactly.
What should I do here?
It depends on where this code is and what you want to happen. If it is in the UI layer - catch it and show a warning; if it's in the service layer - don't catch it at all - let it bubble. Just don't swallow the exception. If an exception occurs in most of the cases you should choose one of these:
log it and return
rethrow it (declare it to be thrown by the method)
construct a new exception by passing the current one in constructor
Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I?
It could've been. But nothing stops you from catching the unchecked exception as well
Why do people add class Exception in the throws clause?
Most often because people are lazy to consider what to catch and what to rethrow. Throwing Exception is a bad practice and should be avoided.
Alas, there is no single rule to let you determine when to catch, when to rethrow, when to use checked and when to use unchecked exceptions. I agree this causes much confusion and a lot of bad code. The general principle is stated by Bloch (you quoted a part of it). And the general principle is to rethrow an exception to the layer where you can handle it.
Whether something is a "checked exception" has nothing to do with whether you catch it or what you do in the catch block. It's a property of exception classes. Anything that is a subclass of Exception except for RuntimeException and its subclasses is a checked exception.
The Java compiler forces you to either catch checked exceptions or declare them in the method signature. It was supposed to improve program safety, but the majority opinion seems to be that it's not worth the design problems it creates.
Why do they let the exception bubble
up? Isnt handle error the sooner the
better? Why bubble up?
Because that's the entire point of exceptions. Without this possibility, you would not need exceptions. They enable you to handle errors at a level you choose, rather than forcing you to deal with them in low-level methods where they originally occur.
Is the above considered to be a checked exception?
No
The fact that you are handling an exception does not make it a Checked Exception if it is a RuntimeException.
Is RuntimeException an unchecked exception?
Yes
Checked Exceptions are subclasses of java.lang.Exception
Unchecked Exceptions are subclasses of java.lang.RuntimeException
Calls throwing checked exceptions need to be enclosed in a try{} block or handled in a level above in the caller of the method. In that case the current method must declare that it throws said exceptions so that the callers can make appropriate arrangements to handle the exception.
Hope this helps.
Q: should I bubble up the exact
exception or mask it using Exception?
A: Yes this is a very good question and important design consideration. The class Exception is a very general exception class and can be used to wrap internal low level exceptions. You would better create a custom exception and wrap inside it. But, and a big one - Never ever obscure in underlying original root cause. For ex, Don't ever do following -
try {
attemptLogin(userCredentials);
} catch (SQLException sqle) {
throw new LoginFailureException("Cannot login!!"); //<-- Eat away original root cause, thus obscuring underlying problem.
}
Instead do following:
try {
attemptLogin(userCredentials);
} catch (SQLException sqle) {
throw new LoginFailureException(sqle); //<-- Wrap original exception to pass on root cause upstairs!.
}
Eating away original root cause buries the actual cause beyond recovery is a nightmare for production support teams where all they are given access to is application logs and error messages.
Although the latter is a better design but many people don't use it often because developers just fail to pass on the underlying message to caller. So make a firm note: Always pass on the actual exception back whether or not wrapped in any application specific exception.
On try-catching RuntimeExceptions
RuntimeExceptions as a general rule should not be try-catched. They generally signal a programming error and should be left alone. Instead the programmer should check the error condition before invoking some code which might result in a RuntimeException. For ex:
try {
setStatusMessage("Hello Mr. " + userObject.getName() + ", Welcome to my site!);
} catch (NullPointerException npe) {
sendError("Sorry, your userObject was null. Please contact customer care.");
}
This is a bad programming practice. Instead a null-check should have been done like -
if (userObject != null) {
setStatusMessage("Hello Mr. " + userObject.getName() + ", Welome to my site!);
} else {
sendError("Sorry, your userObject was null. Please contact customer care.");
}
But there are times when such error checking is expensive such as number formatting, consider this -
try {
String userAge = (String)request.getParameter("age");
userObject.setAge(Integer.parseInt(strUserAge));
} catch (NumberFormatException npe) {
sendError("Sorry, Age is supposed to be an Integer. Please try again.");
}
Here pre-invocation error checking is not worth the effort because it essentially means to duplicate all the string-to-integer conversion code inside parseInt() method - and is error prone if implemented by a developer. So it is better to just do away with try-catch.
So NullPointerException and NumberFormatException are both RuntimeExceptions, catching a NullPointerException should replaced with a graceful null-check while I recommend catching a NumberFormatException explicitly to avoid possible introduction of error prone code.
1 . If you are unsure about an exception, check the API:
java.lang.Object
extended by java.lang.Throwable
extended by java.lang.Exception
extended by java.lang.RuntimeException //<-NumberFormatException is a RuntimeException
extended by java.lang.IllegalArgumentException
extended by java.lang.NumberFormatException
2 . Yes, and every exception that extends it.
3 . There is no need to catch and throw the same exception. You can show a new File Dialog in this case.
4 . FileNotFoundException is already a checked exception.
5 . If it is expected that the method calling someMethod to catch the exception, the latter can be thrown. It just "passes the ball". An example of it usage would be if you want to throw it in your own private methods, and handle the exception in your public method instead.
A good reading is the Oracle doc itself: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.
The next question might be: "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
There's also an important bit of information in the Java Language Specification:
The checked exception classes named in the throws clause are part of the contract between the implementor and user of the method or constructor.
The bottom line IMHO is that you can catch any RuntimeException, but you are not required to and, in fact the implementation is not required to maintain the same non-checked exceptions thrown, as those are not part of the contract.
1) No, a NumberFormatException is an unchecked Exception. Even though you caught it (you aren't required to) because it's unchecked. This is because it is a subclass of IllegalArgumentException which is a subclass of RuntimeException.
2) RuntimeException is the root of all unchecked Exceptions. Every subclass of RuntimeException is unchecked. All other Exceptions and Throwable are checked except for Errors ( Which comes under Throwable).
3/4) You could alert the user that they picked a non-existent file and ask for a new one. Or just quit informing the user that they entered something invalid.
5) Throwing and catching 'Exception' is bad practice. But more generally, you might throw other exceptions so the caller can decide how to deal with it. For example, if you wrote a library to handle reading some file input and your method was passed a non-existent file, you have no idea how to handle that. Does the caller want to ask again or quit? So you throw the Exception up the chain back to the caller.
In many cases, an unchecked Exception occurs because the programmer did not verify inputs (in the case of NumberFormatException in your first question). That's why its optional to catch them, because there are more elegant ways to avoid generating those exceptions.
Checked - Prone to happen. Checked in Compile time.
Eg.. FileOperations
UnChecked - Due to Bad data. Checked in Run time.
Eg..
String s = "abc";
Object o = s;
Integer i = (Integer) o;
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at Sample.main(Sample.java:9)
Here exception is due to bad data and in no way it can be determined during compile time.
Runtime Exceptions :
Runtime exceptions are referring to as unchecked exceptions. All other exceptions
are checked exceptions, and they don't derive from java.lang.RuntimeException.
Checked Exceptions :
A checked exception must be caught somewhere in your code. If you invoke a
method that throws a checked exception but you don't catch the checked exception
somewhere, your code will not compile. That's why they're called checked
exceptions : the compiler checks to make sure that they're handled or declared.
A number of the methods in the Java API throw checked exceptions, so you will often write exception handlers to cope with exceptions generated by methods you didn't write.
Checked exceptions are checked at compile time by the JVM and its related to resources(files/db/stream/socket etc). The motive of checked exception is that at compile time if the resources are not available the application should define an alternative behaviour to handle this in the catch/finally block.
Unchecked exceptions are purely programmatic errors, wrong calculation, null data or even failures in business logic can lead to runtime exceptions. Its absolutely fine to handle/catch unchecked exceptions in code.
Explanation taken from http://coder2design.com/java-interview-questions/
My absolute favorite description of the difference between unchecked and checked exceptions is provided by the Java Tutorial trail article, "Unchecked Exceptions - the Controversy" (sorry to get all elementary on this post - but, hey, the basics are sometimes the best):
Here's the bottom line guideline: If a client can reasonably be
expected to recover from an exception, make it a checked exception. If
a client cannot do anything to recover from the exception, make it an
unchecked exception
The heart of "what type of exception to throw" is semantic (to some degree) and the above quote provides and excellent guideline (hence, I am still blown away by the notion that C# got rid of checked exceptions - particularly as Liskov argues for their usefulness).
The rest then becomes logical: to which exceptions does the compiler expect me to respond, explicitly? The ones from which you expect client to recover.
To answer the final question (the others seem thoroughly answered above), "Should I bubble up the exact exception or mask it using Exception?"
I am assuming you mean something like this:
public void myMethod() throws Exception {
// ... something that throws FileNotFoundException ...
}
No, always declare the most precise exception possible, or a list of such. The exceptions you declare your method as capable of throwing are a part of the contract between your method and the caller. Throwing "FileNotFoundException" means that it is possible the file name isn't valid and the file will not be found; the caller will need to handle that intelligently. Throwing Exception means "Hey, sh*t happens. Deal." Which is a very poor API.
In the comments on the first article there are some examples where "throws Exception" is a valid and reasonable declaration, but that's not the case for most "normal" code you will ever write.
I think that checked exceptions are a good reminder for the developer that uses an external library that things can go wrong with the code from that library in exceptional situations.
Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up?
For example let say you have some client-server application and client had made a request for some resource that couldn't be find out or for something else error some might have occurred at the server side while processing the user request then it is the duty of the server to tell the client why he couldn't get the thing he requested for,so to achieve that at server side, code is written to throw the exception using throw keyword instead of swallowing or handling it.if server handles it/swallow it, then there will be no chance of intimating to the client that what error had occurred.
Note:To give a clear description of what the error type has occurred we can create our own Exception object and throw it to the client.
I just want to add some reasoning for not using checked exceptions at all. This is not a full answer, but I feel it does answer part of your question, and complements many other answers.
Whenever checked exceptions are involved, there's a throws CheckedException somewhere in a method signature (CheckedException could be any checked exception). A signature does NOT throw an Exception, throwing Exceptions is an aspect of implementation. Interfaces, method signatures, parent classes, all these things should NOT depend on their implementations. The usage of checked Exceptions here (actually the fact that you have to declare the throws in the method signature) is binding your higher-level interfaces with your implementations of these interfaces.
Let me show you an example.
Let's have a nice and clean interface like this
public interface IFoo {
public void foo();
}
Now we can write many implementations of method foo(), like these
public class Foo implements IFoo {
#Override
public void foo() {
System.out.println("I don't throw and exception");
}
}
Class Foo is perfectly fine. Now let's make a first attempt at class Bar
public class Bar implements IFoo {
#Override
public void foo() {
//I'm using InterruptedExcepton because you probably heard about it somewhere. It's a checked exception. Any checked exception will work the same.
throw new InterruptedException();
}
}
This class Bar won't compile. As InterruptedException is a checked exception, you must either capture it (with a try-catch inside method foo()) or declare that you're throwing it (adding throws InterruptedException to the method signature). As I don't want to capture this exception here (I want it to propagate upwards so I can properly deal with it somewhere else), let's alter the signature.
public class Bar implements IFoo {
#Override
public void foo() throws InterruptedException {
throw new InterruptedException();
}
}
This class Bar won't compile either! Bar's method foo() does NOT override IFoo's method foo() since their signatures are different. I could remove the #Override annotation, but I want to program against interface IFoo like IFoo foo; and later on decide on which implementation I want to use, like foo = new Bar();. If Bar's method foo() doesn't override IFoo's method foo, when I do foo.foo(); it won't call Bar's implementation of foo().
To make Bar's public void foo() throws InterruptedException override IFoo's public void foo() I MUST add throws InterruptedException to IFoo's method signature. This, however, will cause problems with my Foo class, since it's foo() method's signature differs from IFoo's method signature. Furthermore, if I added throws InterruptedException to Foo's method foo() I would get another error stating that Foo's method foo() declares that it throws an InterruptedException yet it never throws an InterruptedException.
As you can see (if I did a decent job at explaining this stuff), the fact that I'm throwing a checked exception like InterruptedException is forcing me to tie my interface IFoo to one of it's implementations, which in turn causes havoc on IFoo's other implementations!
This is one big reason why checked exceptions are BAD. In caps.
One solution is to capture the checked exception, wrap it in an unchecked exception and throw the unchecked exception.
Java distinguishes between two categories of exceptions (checked & unchecked).
Java enforces a catch or declared requirement for checked exceptions.
An exception's type determines whether an exception is checked or unchecked.
All exception types that are direct or indirect subclasses of class RuntimeException
are unchecked exception.
All classes that inherit from class Exception but not RuntimeException are considered to be checked exceptions.
Classes that inherit from class Error are considered to be unchecked.
Compiler checks each method call and deceleration to determine whether the
method throws checked exception.
If so the compiler ensures the exception is caught or is declared in a throws clause.
To satisfy the declare part of the catch-or-declare requirement, the method that generates
the exception must provide a throws clause containing the checked-exception.
Exception classes are defined to be checked when they are considered important enough to catch or declare.
Here is a simple rule that can help you decide. It is related to how interfaces are used in Java.
Take your class and imagine designing an interface for it such that the interface describes the functionality of the class but none of the underlying implementation (as an interface should). Pretend perhaps that you might implement the class in another way.
Look at the methods of the interface and consider the exceptions they might throw:
If an exception can be thrown by a method, regardless of the underlying implementation (in other words, it describes the functionality only) then it should probably be a checked exception in the interface.
If an exception is caused by the underlying implementation, it should not be in the interface. Therefore, it must either be an unchecked exception in your class (since unchecked exceptions need not appear in the interface signature), or you must wrap it and rethrow as a checked exception that is part of the interface method.
To decide if you should wrap and rethrow, you should again consider whether it makes sense for a user of the interface to have to handle the exception condition immediately, or the exception is so general that there is nothing you can do about it and it should propagate up the stack. Does the wrapped exception make sense when expressed as functionality of the new interface you are defining or is it just a carrier for a bag of possible error conditions that could also happen to other methods? If the former, it might still be a checked exception, otherwise it should be unchecked.
You should not usually plan to "bubble-up" exceptions (catch and rethrow). Either an exception should be handled by the caller (in which case it is checked) or it should go all the way up to a high level handler (in which case it is easiest if it is unchecked).
Just to point out that if you throw a checked exception in a code and the catch is few levels above, you need to declare the exception in the signature of each method between you and the catch. So, encapsulation is broken because all functions in the path of throw must know about details of that exception.
In short, exceptions which your module or modules above are supposed to handle during runtime are called checked exceptions; others are unchecked exceptions which are either RuntimeException or Error.
In this video, it explains checked and unchecked exceptions in Java:
https://www.youtube.com/watch?v=ue2pOqLaArw
All of those are checked exceptions. Unchecked exceptions are subclasses of RuntimeException. The decision is not how to handle them, it's should your code throw them. If you don't want the compiler telling you that you haven't handled an exception then you use an unchecked (subclass of RuntimeException) exception. Those should be saved for situations that you can't recover from, like out of memory errors and the like.
Checked Exceptions :
The exceptions which are checked by the compiler for smooth execution of the program at runtime are called Checked Exception.
These occur at compile time.
If these are not handled properly, they will give compile time error (Not Exception).
All subclasses of Exception class except RuntimeException are Checked Exception.
Hypothetical Example - Suppose you are leaving your house for the exam, but if you check whether you took your Hall Ticket at home(compile time) then there won't be any problem at Exam Hall(runtime).
Unchecked Exception :
The exceptions which are not checked by the compiler are called Unchecked Exceptions.
These occur at runtime.
If these exceptions are not handled properly, they don’t give compile time error. But the program will be terminated prematurely at runtime.
All subclasses of RunTimeException and Error are unchecked exceptions.
Hypothetical Example - Suppose you are in your exam hall but somehow your school had a fire accident (means at runtime) where you can't do anything at that time but precautions can be made before (compile time).
If anybody cares for yet another proof to dislike checked exceptions, see the first few paragraphs of the popular JSON library:
"Although this is a checked exception, it is rarely recoverable. Most callers should simply wrap this exception in an unchecked exception and rethrow: "
So why in the world would anyone make developers keep checking the exception, if we should "simply wrap it" instead? lol
http://developer.android.com/reference/org/json/JSONException.html
All exceptions must be checked exceptions.
Unchecked exceptions are unrestricted gotos. And unrestricted gotos are considered a bad thing.
Unchecked exceptions break encapsulation. To process them correctly, all the functions in the call tree between the thrower and the catcher must be known to avoid bugs.
Exceptions are errors in the function that throws them but not errors in the function that processes them. The purpose of exceptions is to give the program a second chance by deferring the decision of whether it's an error or not to another context. It's only in the other context can the correct decision be made.

difference between checked exceptions and compile time exceptions? [duplicate]

This question already has answers here:
Differences between Runtime/Checked/Unchecked/Error/Exception
(8 answers)
Closed 7 years ago.
I heard there is difference between compile time exceptions and checked exceptions.But, logically couldn't find any .Please help
A common misconception is that all errors are exceptions. When a new user sees an error or stack trace it must be an exception. However this is not the case. You can get
compile time errors such as syntax errors which are not exceptions in any sense.
exception which occur in the compiler it self. This is not due to an error in your code but a bug in the compiler.
a stack trace for debugging purposes which is not an error. It's just a stack trace of where the program was when something happened.
Most likely, the person was confused about what is an error reported by the compiler and an actual error which occurs when you run the program.
P.S. It is unlikely but the person could have been thinking that "Checked Exception" usually refers to Exception or sub-classes which are not RuntimeException or sub-classes.
This is not all Throwable which are checked at compile time. In fact all Throwable are checked exception RuntimeException and Error and their sub-classes. This means you can sub-class Throwable (which is almost never used) or create Throwable itself, which is almost never thrown and only used for logging.
Checked exceptions are checked at compile-time. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. It is named as checked exception because these exceptions are checked at Compile time.
There is no difference between compile time exceptions and checked exceptions

Why must only certain Exceptions be declared as thrown in method signature

when declaring a methods with "IllegalAccessException" eclipse forces me to
declare the method as throwing an exception
public void a() throws IllegalAccessException {
if(x == 1){
throw new IllegalAccessException("TEST);
}
}
and in method b that uses "IllegalStateException" i dont need to declare the method as throw an exception
public void b() {
if(x == 1){
throw new IllegalStateException("TEST);
}
}
what is the different between thous exception
that one forces me tho declare the method that throw an exception
and the other is not
thank you
Because IllegalAccessException is not RuntimeException (i.e. is checked exception) and IllegalStateException is a RuntimeException (i.e. is unchecked exception).
Read this for more information: Difference between java.lang.RuntimeException and java.lang.Exception
And this explanation on Oracle site: http://download.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html
The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from. For example, suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name.
Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.
The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem — but it also might make sense for the program to print a stack trace and exit.
Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.
The third kind of exception is the runtime exception. These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API. For example, consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur.
Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses.
IllegalAccessException is a checked exception. Checked exceptions must be declared or handled as they are expected results of an operation.
IllegalStateException is an unchecked exception. Unchecked exception are generally considered programming errors and it is not expected to receive one as part of normal program execution. When a programming error does occur, these exceptions are printed to standard error by default with a stack trace so the developer can determine what the programming error was.
As you can see in the Javadoc of the JDK, the IllegalStateException is a RuntimeException, which is not the case of the IllegalAccessException.
And as stated by this Javadoc:
RuntimeException is the superclass of
those exceptions that can be thrown
during the normal operation of the
Java Virtual Machine.
A method is not required to declare in
its throws clause any subclasses of
RuntimeException that might be thrown
during the execution of the method but
not caught.
That explains the difference.
It's part of the Java design that some exceptions need 'throw' declarations and some don't. Those that don't are called 'run time exceptions' and descend from "RuntimException". IllegalAccessException is not a runtime exception, and IllegalStateException is.
The logic behind the difference is that general exceptions are intended for exceptional cases that might occur at any time, no matter what the programmer does, and should always be handled by the programmer if they want their code to be rebust. An IllegalAccessException, or an IO Excection, might be caused by a failure of hardware, or access permissions, which are outside the programmers control. The software needs to do something when they occur, and having a throws clause forces the programmer to think about what to do. IllegalStateException is a symptom of a programmer error of some kind, and so doesn't necessarily need to be handled.

How to differentiate between Programmer and JVM Exceptions

As the title suggests, how can I tell a JVM thrown exception from a Programmatically(does this mean, thrown by a programmer or the program) thrown exception ?
JVM Exceptions
1) ArrayIndexOutOfBoundsException
2) ClassCastException
3) NullPointerException
Programmatically thrown
1) NumberFormatException
2) AssertionError
Many Thanks
How to differentiate between Programmer and JVM Exceptions
You cannot do this statically because no such distinction exists.
Any exception defined in the standard Java class libraries may be thrown by application or third-party library code. This includes exceptions (including those that you listed) that are normally thrown by the JVM itself.
In some cases, it is a bad (or even terrible) idea to throw a standard exception. For example, it would be a really bad idea for an application to throw something like VerifyError because that has a very specific meaning that an application has no business throwing.
In other cases, there are no issues. For example, there is no problem1 with an application throwing NullPointerException explicitly; e.g.
public void setName(String name) {
if (name == null) {
throw new NullPointerException("name must not be null");
}
this.name = name;
}
The only possible way to distinguish between an exception that has been thrown by the JVM and by application code is to examine the stack frames from the thrown exception to figure out what class instantiated the exception. (Strictly speaking that doesn't tell you where the exception was thrown ... but it is close enough given that exceptions are nearly always instantiated and thrown in the same statement.)
But even this is not a useful distinction to make. There is no semantically useful difference between an exception thrown by application code, the standard class library or the JVM itself. The source of the exception certainly doesn't say anything about the root cause of the problem; e.g. whether it is due to an application bug, a library bug or something else.
The only useful distinctions are:
Error exceptions which you should not attempt to recover from, because they are usually not recoverable.
Other unchecked exceptions which may be recoverable, but are typically caused by bugs.
Checked exceptions which are often caused by "environmental" problems (such as incorrect file names) that may well need to be reported to the user.
There are a couple of alternative readings of the question:
If you wanted to distinguish the exceptions that could be thrown by the JVM from those that can only be thrown by Java code, you could do this by searching the OpenJDK source code for places where exceptions are thrown from native code.
If you wanted to distinguish the exceptions that could be thrown by the JVM OR by the standard Java libraries, broaden the search to include Java source code.
However, in both cases the "answer" is not useful (as above), and will depend on the particular Java release you examine.
1 - 1) There are no technical problems with throwing NPE, CCE, AIOOBE and so on. 2) I have never come across a style guide that says you shouldn't do it. 3) I have never seen a coherent explanation of why it should be "frowned on". (If you know of one, please provide a link to it.)
I'm not sure what you mean by JVM exceptions. These are all runtime exceptions that may be thrown by the programmer at any point (exception AssertionError), though it is considered poor style to throw certain exceptions like NullPointerException. The point is, there's no one quality separating the two categories you mention other than their typical usage. All the runtime exceptions extend, either directly or indirectly, RuntimeException.
From the JavaDocs for Throwable:
Only objects that are instances of
this class (or one of its subclasses)
are thrown by the Java Virtual Machine
or can be thrown by the Java throw
statement.
Because this same superclass defines all exceptions thrown by either the JVM or a programmer, you can't easily distinguish the two.
I don't think you will find a complete list, since there is no clear distinction between jvm and programmer initiated exceptions, apart from a few special cases:
most Error classes are thrown by the VM, due to internal or external causes. The one exception ThreadDeath, is thrown in a thread when that thread is stopped, and is kind of a "hack" to get the thread to unwind it's stack and exit.
most checked exceptions relate to environmental problems that lead to failure of some operation, but may be resolvable and are non-fatal to the JVM (IOException, SQLException, RemoteException) come to mind.
the remainder, unchecked exceptions, are a combination of both jvm and programmer initiated exception. For example, the JDK throws IllegalArgumentException when method parameters are not to spec. Is that a JVM exception or a programmatic exception? It unclear if your definition of JVM exceptions includes the JDK or not. ArrayIndexOutOfBounds is generated for illegal array accesses, generated by the JVM, but it's also thrown in some apis, e.g. Track.get from java.midi. (Although this can be argued as poor form, and the superclass IndexOutOfBounds should have been used instead.)
The most used exceptions thrown by JVM and by API are:
Exceptions thrown by JVM
ArrayIndexOutOfBoundsException
ClassCastException
NullPointerException
ArithmeticException
AssertionError
ExceptionInInitializerError
StackOverflowError
NoClassDefFoundError
Programmatically by API thrown
llegalArgumentException
NumberFormatException
IllegalStateException
SecurityException
Where exceptions come from
It's important that you understand what causes exceptions and errors and where they come from. Java defines two broad categories of exceptions and errors:
JVM exceptions: those exceptions or errors that are either exclusively or
most logically thrown by the JVM
Programmatic exceptions: those exceptions that are thrown explicitly by
application and/or API programmers
A very common exception, the NullPointerException occurs when you attempt to access an object using a reference variable with a current value of null. There's no way that the compiler can hope to find those problems before runtime. Take a look at the following:
class NPE {
static String s;
public static void main(String [] args) {
System.out.println(s.length());
}
}

Java Terminology: Why compile-time error and not compile-time exception?

This may sound awkward ...
But I didn't understand it.
Why do we have compile-time error and not compile-time exception in java ?
I mean to say that we never say compile-time exception.
We tend to say it as compile-time error.
Is there any specific reason for the same ??
Any suggestions are welcomed....
Thanks !
The reason for this is that an exception is something thrown during execution of a program. Java has a specific type for this, the Exception class.
At compile time, your code is not executing, so it cannot throw an exception. Indeed, it is proper execution of the compiler to find errors in your code - certainly not an exception case!
Exception in java is really different than compile error. We don't have the term compile time exception. Because exception is something happens that you don't expect it to happen. We only have checked and unchecked exception. With checked exception, in compile time, the compiler will force you to catch it, but it is not an error. Don't catch it, you can not compile the program but it is not a compile error.
An error indicates that there is a problem with the program. An exception is a specific construct that interrupts the control flow of the program, and unwinds the stack, capturing information about the state of the stack so that it can be reported.
An exception can be used to indicate an error, but not always. For example:
void startOperation() {
try {
while (someComplexOperationIsOnGoing()) {
checkRestart();
}
}
catch (RestartException re) {
startOperation();
}
}
void checkRestart() {
if (shouldRestart()) {
throw new RestartException();
}
}
This incomplete code sample is meant to show a case where an exception is not an error. This is not always best practice; but it is used in some cases where the intent is to interrupt the control flow deep in the program (such as redirecting the page in a web framework, when responding to an HTTP request) and return control to a higher-up level of the stack. The term exception refers to the mechanism which interrupts the program.
In java, there is an Exception class which encapsulates this behavior. The Error class also interrupts the control flow in the same way as an Exception; but it is reserved only for serious, unrecoverable problems that happen at runtime. It is used, for example, when the JVM runs out of memory and can't create new objects.
Exception is something more of an unexpected flow that can be handled.
Compile time error is more like invalid code..so code doesn't even compile..
Hence term "error" since it denotes more serious problem which has to be fixed.
Compile time errors are the result of the inability of the software to be created as it is instructed. For instance:
String myString = new ButtonEvent();
is a compile time error. While an exception is something that is caught during software processing.
try{
while( file.readNextLine() != file.EOF ){
}
}
catch( UnopenedException ex ){
}
Here, we've made the assumption that the file could be properly opened and had been. The exception is for those "exceptional" cases where opening the file didn't occur.
An exception is the specific name for an error that can be handled within the logic of your software. An error is simply that, a typo or just plain wrong code.

Categories

Resources