What is Exception?
Exception is an abnormal event that occurs during program execution and disrupts the normal flow of the program's instructions.
Exception is a object which is throws at runtime.
What is Error?
Error in java are categorised into two groups:Compile-time error and Run-time error.
Compile-time error: It occurs when we do not follow the syntax of programming language.
Eg.In java, we need to terminate every expression with a semicolon(;).If you do not follow this rule you get a compile time error.
Run-time error: An exception is a run-time error that occurs during execution of the program.
Eg.If we divide a number by zero or open a file that does not exist,an exception is raised.
What is Checked Exception?
Exceptions that are checked at compile-time are called checked exceptions.In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.
Example:
Exception | Reason for Exception |
---|---|
ClassNotFoundException | This Exception occurs when Java run-time system fail to find the specified class mentioned in the program |
Instantiation Exception | This Exception occurs when you create an object of an abstract class and interface |
Illegal Access Exception | This Exception occurs when you access private members. |
Not Such Method Exception | This Exception occurs when the method you call does not exist in class |
What is Unchecked Exception?
Exceptions that are checked at run time are called unchecked exceptions, classes that extends RuntimeException comes under unchecked exceptions.
Example:
Exception | Reason for Exception |
---|---|
Arithmetic Exception | These Exception occurs, when you divide a number by zero causes an Arithmetic Exception |
Class Cast Exception | These Exception occurs, when you try to assign a reference variable of a class to an incompatible reference variable of another class |
Array Store Exception | These Exception occurs, when you assign an array which is not compatible with the data type of that array |
Array Index Out Of Bounds Exception | These Exception occurs, when you assign an array which is not compatible with the data type of that array |
Null Pointer Exception | These Exception occurs, when you try to implement an application without referencing the object and allocating to a memory |
Number Format Exception | These Exception occurs, when you try to convert a string variable in an incorrect format to integer (numeric format) that is not compatible with each other |
Negative ArraySizeException | These are Exception, when you declare an array of negative size. |
How Exception Terminates Java Program?
Whenever exception arises, it terminates the program execution, means it stops the execution of the current java program.
Example:
class Demo { public static void main(String a[]){ System.out.println(10/0); } }Try it Yourself
How the Exception is handled in java?
We can implement exception handling in java by using following keywords.
- try
- catch
- throw
- throws
- finally
How to use try block?
The functionality of try keyword is to identify an exception object and transfer the control to the catch block by suspending the execution of the try block.
All the statements which are proven to generate exceptions should be place in try block.
Syntax:
try { //try block //keep those statements which may //throw run time exceptions }
How to use catch Block?
The functionality of catch block is to receive the exception class object that has been send by the "try" and handle the exception that has been identified by "try".
"try" block identifies an exception and "catch" block handles the identified exception.
Syntax:
catch(Exception e) { //catch block. //catches the exceptions thrown by try block }
Example:
class MyExceptionHandle { public static void main(String a[]){ try{ System.out.println(10/0); } catch(Exception ex){ System.out.println("Exception divide by zero"); } } }Try it Yourself
Can we use multiple catch for try block ?
Yes,We can use multiple catch for try block.
Example:
class Demo{ public static void main(String args[]){ int num1=1,num2=0,result=0; try{ result = num1/num2; System.out.println("The result is:" + result); } catch(ArithmeticException e){ System.out.println("Error...Division by Zero"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Error...Out of Bounds"); } catch(NumberFormatException e){ System.out.println("Not able to convert the values from string to integer"); } catch(Exception e){ System.out.println("General Exception"); } } }Try it Yourself
What is finally block?
A finally block is always executed irrespective of an exception being raised or not.
Syntax:
finally{ //This is the finally block. }
Example:
class TestFinally{ public static void main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(ArithmeticException e){ System.out.println("Numer divided by zero"); } finally{ System.out.println("finally block is always executed"); } } }Try it Yourself
What is printStackTrace()?
When an exception is caught,you can find out the method or line of the code where the exception is raised by using the printStackTrace() method.
It is used to print the stack trace to check the line in the code where the exception is raised.
Example:
class Print_stack{ public static void main(String[] args){ int num1=20,num2=0; try{ int num3=num1/num2; } catch(ArithmeticException obj){ obj.printStackTrace(); } } }Try it Yourself
What is throw keyword?
The throw keyword causes the termination of the normal flow of control of the java code and stops the execution of the subsequent statements.
The throw keyword tranfers the control to the nearest catch block that handles the type of exception being thrown.
If no appropriate catch block exists,the program terminates.
Syntax:
throw ThrowableInstance
Example:
class ThrowDemo { public void method(){ try{ throw new NullPointerException("explicitly throw the exception"); } catch(Exception e){ System.out.println(e); } } public static void main(String agrs[]){ ThrowDemo obj= new ThrowDemo(); obj.method(); } }Try it Yourself
What is throws keyword?
The throws keyword is used by a method to specify the types of exceptions the method can throw.
The throws keyword lists the types of exception that a method can throw.
Syntax:
type method_name(parameter_list) throws exception_list { //definition of method }
Example:
class ThrowsDemo { public void method() throws ArithmeticException{ try{ int a=5,b=0,c; c= a/b; }catch(ArithmeticException e){ System.out.println(e); } } public static void main(String agrs[]){ ThrowsDemo obj= new ThrowsDemo(); obj.method(); } }Try it Yourself
How to Create Java Custom Exception?
we can also create our own Exceptions nothing but User defined Exceptions.
User defined exceptions in java are also known as Custom exceptions.
Example:
class InvalidAgeException extends Exception{ InvalidAgeException(String s){ super(s); } } class Demo{ static void validate(int age) throws InvalidAgeException{ if(age<18){ throw new InvalidAgeException("Not Valid"); } else{ System.out.println("Welcome to Vote"); } } public static void main(String args[]){ try{ validate(13); } catch(Exception m){ System.out.println("Exception occured: "+m); } } }Try it Yourself
Solve this!!
class exception_handling { public static void main(String args[]) { try { System.out.print("Hello" + " " + 1 / 0); } catch(ArithmeticException e) { System.out.print("World"); } } }
In System.out.print() function :1 / 0 Exception is encountered which is cached by catch block printing just “World” .
class exception_handling { public static void main(String args[]) { try { int a, b; b = 0; a = 5 / b; System.out.print("A"); } catch(ArithmeticException e) { System.out.print("B"); } finally { System.out.print("C"); } } }
finally block is always executed irrespective of an exception being raised or not.
- Collection
- ArrayList
- LinkedList
- Vector
- HashSet
- Conditional Statements
- Classes and Objects
- Inheritance
- Packages
- Exception Handling
- Threads
- TreeSet
- LinkedHashSet
- HashMap
- TreeMap
- LinkedHashMap
- HashTable
- Iterator and ListIterator
- String
- Scanner
- Array Small Programs
- Introduction
- Variables
- DataTypes
- Operators
- Conditional Statements
- Loop
- Arrays
- Object Oriented Programming
- Classes and Objects
- Access Modifiers
- Methods
- Abstraction
- Constructor
- Packages
- StringBuffer
- Inheritance
- StringBuilder
- Encapsulation
- Java IO
- Polymorphism
- Interface
- Types Of Variables
- Static Keyword
- Final Keyword
- Super Keyword
- This Keyword
- Exception Handling