1)https://www.javatpoint.com/exception-handling-in-java
2)https://www.quora.com/What-is-difference-between-a-checked-and-unchecked-exception
2)https://www.quora.com/What-is-difference-between-a-checked-and-unchecked-exception
Unchecked: “Error” and its subclasses,”RunTimeException” and its subclasses
Checked: Every exception other than Unchecked exception
Checked Exception: These are the exceptions which may occur regularly in a program and compiler will check for those exceptions at “Compile Time” ,those exceptions are called Checked Exceptions
Example: FileNotFoundException, EndOfFileException etc.
So the compiler at compile time will check if a certain method is throwing any of the checked exceptions or not,if yes it will check whether the method is handling that exception either with “Try&Catch” or “throws”,if in case the method is not providing the handling code then compiler will throw error saying “Unreported Exception”
For example
- import java.io.*
- Class Example
- {
- public static void main(String[] args)
- {
- PrintWriter pw=new PrintWriter("xyz.txt"); //creating a new printwriter object to write in a file named "xyz.txt"
- pw.println("Hello World");
- } }
The above snippet is supposed to print “Hello World” in file named “xyz.txt”
There may be a chance of file “xyz.txt” is not present in specified directory,so the compiler will check if any handling code is provided in case file is not present
In above snippet handling code is not provided either with “Try&Catch” or “throws” so the compiler will throw error
The same example with some modification:
- import java.io.*
- Class Example
- {
- public static void main(String[] args) throws FileNotFoundException
- {
- PrintWriter pw=new PrintWriter("xyz.txt"); //creating a new printwriter object to write in a file named "xyz.txt"
- pw.println("Hello World");
- }}
In this example handling code is provided with “throws” so compiler will not throw any error.
Unchecked Exceptions:
There are some exceptions which do not occur regularly in a program,and compiler will not check for those exceptions,these kind of exceptions are called Unchecked Exceptions
Example: ArithmeticException, NullPointerException etc
For example:
- class Example{
- public static void main(String[] args){
- System.out.println(10/0); //Arithmetic Exception
- }
- }
The above program should throw “Arithmetic Exception” as division with “0” is not allowed
In this case the program compiles fine because compiler will not check for “Unchecked Exceptions” but the program will throw error at “Run Time” as division with “0” is illegal.
P.S: All the exceptions occurs at “Run Time” only.
writing this line because many people think that “Checked Exceptions” occurs at Compile time and “Unchecked Exceptions” occurs at Run time,which is not the case.
Q3)What is the difference between an exception and error?
An exception is an event that represents a condition from which is possible to recover, whereas error represents an external situation usually impossible to recover from.
All errors thrown by the JVM are instances of Error or one of its subclasses, the more common ones include but are not limited to:
- OutOfMemoryError – thrown when the JVM cannot allocate more objects because it is out memory, and the garbage collector was unable to make more available
- StackOverflowError – occurs when the stack space for a thread has run out, typically because an application recurses too deeply
- ExceptionInInitializerError – signals that an unexpected exception occurred during the evaluation of a static initializer.
- NoClassDefFoundError – is thrown when the classloader tries to load the definition of a class and couldn’t find it, usually because the required class files were not found in the classpath
- UnsupportedClassVersionError – occurs when the JVM attempts to read a class file and determines that the version in the file is not supported, normally because the file was generated with a newer version of Java
Although an error can be handled with a try statement, this is not a recommended practice since there is no guarantee that the program will be able to do anything reliably after the error was thrown.
Q4. What exception will be thrown executing the following code block?
Integer[][] ints = { {
1
,
2
,
3
}, {
null
}, {
7
,
8
,
9
} };
System.out.println(
"value = "
+ ints[
1
][
1
].intValue());
Ans:
It throws an ArrayIndexOutOfBoundsException since we’re trying to access a position greater than the length of the array.Q5. What is exception chaining?
Ans:
Occurs when an exception is thrown in response to another exception. This allows us to discover the complete history of our raised problem:
1
2
3
4
5
| try { task.readConfigFile(); } catch (FileNotFoundException ex) { throw new TaskException( "Could not perform task" , ex);
}
Q6. What is a stacktrace and how does it relate to an exception?
Ans:
A stack trace provides the names of the classes and methods that were called, from the start of the application to the point an exception occurred.
It’s a very useful debugging tool since it enables us to determine exactly where the exception was thrown in the application and the original causes that led to it.
Q7. Can you throw any exception inside a lambda expression’s body?
When using a standard functional interface already provided by Java, you can only throw unchecked exceptions because standard functional interfaces do not have a “throws” clause in method signatures:
However, if you are using a custom functional interface, throwing checked exceptions is possible:
Q13. What are the rules we need to follow when overriding a method that throws an exception?
Several rules dictate how exceptions must be declared in the context of inheritance.
When the parent class method doesn’t throw any exceptions, the child class method can’t throw any checked exception, but it may throw any unchecked.
Here’s an example code to demonstrate this:
The next example will fail to compile since the overriding method throws a checked exception not declared in the overridden method:
When the parent class method throws one or more checked exceptions, the child class method can throw any unchecked exception; all, none or a subset of the declared checked exceptions, and even a greater number of these as long as they have the same scope or narrower.
Here’s an example code that successfully follows the previous rule:
Note that both methods respect the rule. The first throws fewer exceptions than the overridden method, and the second, even though it throws more; they’re narrower in scope.
However, if we try to throw a checked exception that the parent class method doesn’t declare or we throw one with a broader scope; we’ll get a compilation error:
When the parent class method has a throws clause with an unchecked exception, the child class method can throw none or any number of unchecked exceptions, even though they are not related.
Here’s an example that honors the rule:
Q14. Will the following code compile?
Yes. When chaining exceptions, the compiler only cares about the first one in the chain and, because it detects an unchecked exception, we don’t need to add a throws clause.
Q15. Is there any way of throwing a checked exception from a method that does not have a throws clause?
Yes. We can take advantage of the type erasure performed by the compiler and make it think we are throwing an unchecked exception, when, in fact; we’re throwing a checked exception:
|
No comments:
Post a Comment