An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error.
The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler.
If no exception handlers are found then the run time system terminates.
Throw keyword is used to throw an exception. Any method can throw an exception.
Throw has one parameter - a throwable objects.
Two types of throwable objects are errors, exceptions and their descendants.
e.g.
public Object pop() {
Object obj;
if (size == 0) {
throw new EmptyStackException();
}
.....
}
But throws keyword is used to specify that the method may throw an exception. It gives an information to the programmer that there may occur an exception so programmer has to provide the exception handling code.
Exceptions in Java can be of two types - checked and unchecked. Runtime exceptions are unchecked exceptions.
Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.
Some common examples of runtime exceptions are
ArithmeticException
IndexOutOfBoundsException
ClassCastException
CheckedExceptions are those exceptions which are caught at compile time. These exceptions must be either handled in the current method or they must be thrown. If they are neither handled, nor thrown, the compiler will give an error.
Another type of exception is Unchecked exception or Runtime exception. These need not be handled or thrown.
An example of checked exception is IOException.
final keyword is with class, method or a field. A final class can not be sub-classed. A final method can not be over ridden. A final field can not be modified (like a constant)
Finally is a block used in exception handling. This block is always executed irrespective of whether the exception is handled or not.
Exception is an event during a program execution which disrupts the normal execution of the program.
Exception handling is the process of responding to exceptions when a computer program runs.
Exception handling attempts to gracefully handle these situations so that a program (or worse, an entire system) does not crash.
throw is used to throw an exception. But throws is used to specify what types of exception a function may throw.
e.g.
int readFile(String filename) throws IOException,MyException{
if(filename==null)
throw MyException;
}
Here the function may throw IOException if there is an error in file operation.
In a function if the filename is null, then we are throwing an exception of the type MyException
import java.util.Scanner; public class ExceptionTest { public static void main(String args[]){ int n1,n2; Scanner scanner = new Scanner(System.in); System.out.println("Enter two numbers :"); n1 = scanner.nextInt(); n2 = scanner.nextInt(); if(n2==0){ try { throw new ArithmeticException(); } catch (ArithmeticException e) { System.out.println("Divide by zero. Arithmetic exception..."); e.printStackTrace(); } }else{ System.out.println("The quotient is "+n1/n2); } } }
Note : ArithmeticException is an unchecked exception. So it is not compulsory to throw or handle it.
A checked exception is verified at compile time. If there is a possibility of checked exception thrown, then the code must either catch this exception and handle it or mention it in exception specifier of the method.
e.g.
IOException
An uncheked exception is a run time exception. This exception need not be handled, nor specified in the throws specifier of the method. All run time exceptions are unchecked exception.
e.g.
ArrayIndexOutofBoundException
ArithmeticException
Errors and Exceptions are both subclasses of Throwable class. Errors are normally caused by enviroment - like memory out of error. Exceptions are caused by application itself.
Recovering from errors is not possible but you can recover from exceptions using try-catch blocks are throwing the exception back to calling function.
Errors happen at run time. Exceptions happen at compile time.
Errors are always unchecked. Exceptions can be either checked or unchecked.
Like other objects, even exception objects will be garbage collected after exception handling.
Runtime exceptions are unchecked exceptions. These exceptions happen because of environment like memory error etc. Run time exceptions need not be caught or handled.
To create our own exceptions, we have to extend the Exception class with a constructor with a string parameter. When a program throws such an exception, it must be either handled or propated.
throw keyword is used in Java to throw an exception. throw can be used to throw either a checked or an unchecked exception.
throw exception;
If it is a checked exception, then the code must either handle the exception using try-catch block or the function must specify this exception in the exception specification.
Checked exceptions, errors and run time exceptions
Yes. Since Java 7, a catch block can specify multiple exception types. And it is done using | operator.
e.g.
try{
FileReader reader = new FileReader("a.txt");
if(reader!=null){
int m = reader.read();
int n = reader.read();
int ans = m/n;
}
catch(IOException|ArithmeticException e){
System.out.println("Exception");
}
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it.
The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
Here br the BufferedReader is automatically closed when try block is completed.
Prior to Java 7, this was accomplished using finally block
If a parent class method throws no exception, then the overriding method can not throw any checked exceptions. It can throw unchecked exceptions.
If the parent class method throws checked exceptions, then the overriding method can throw child exceptions(narrower) of the super class exceptions or no exceptions at all.
A code which may throw an exception is enclosed in try block. This try block is followed by one or more catch blocks. When and if an exception is thrown, the catch block whose type matches with the thrown exception type is executed - the code inside this catch block is executed.
A try block may have an optional finally block at the end. This finally block is executed irrespective of whether the exception is thrown or not.
e.g.
try{
}
catch (type1 e){
...
}
catch (type2 e){
}
...
finally{
}
When we throw another exception as a response to an exception, it is called exception chaining.
e.g.
try{
File f1 = new File("myfile");
}catch(FileNotFoundException e){
throw new Exception("file error");
}
From a regular lambda function, we can only throw unchecked exception.
But if we use a FunctionInterface, then we can throw an exception
int n,d; n = scanner.nextInt(); d = scanner.nextInt(); if(d==0) throw new RuntimeException(new Exception("Division error"); else System.out.println(n/d);
Yes it does.
When we use the exception
chaining, JVM is only bothered about outermost exception type. In this case, it is unchecked exception
- which need not be handled. So the program compiles OK