Table of contents Show
Exception handling in java is one of the powerful mechanisms to handle runtime errors caused by exceptions. Exception handling plays an important role in software development. This article helps you understand java exception, exception in java, java exception handling, java exception hierarchy, types of exception in java, and many more.
What is Exception Handling in Java?Exception handling in java helps in minimizing exceptions and helps in recovering from exceptions. It is one of the powerful mechanisms to handle runtime exceptions and makes it bug-free. Exception handling helps in maintaining the flow of the program. An exception handling is defined as an abnormal condition that may happen at runtime and disturb the normal flow of the program. Also Read: Java Tutorial for beginners What is an Exception?An expectation is an unexpected event that occurs while executing the program, that disturbs the normal flow of the code. Exception handling in java with an example: Let’s say, statement statement statement exception ………… an exception occurred, then JVM will handle it and will exit the prog. statement statement statementFor handling exceptions, there are 2 possible approaches 1. JVMIf an exception is not handled explicitly, then JVM takes the responsibility of handling the exception. Once the exception is handled, JVM will halt the program and no more execution of code will take place
Runtime Error: Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(File.java:5)2. DeveloperDevelopers can explicitly write the implementation for handling the exception. Once an exception is handled, the normal execution of code will continue. Preferable: handle exceptions to ensure your code gets executed normally. Java Exception HierarchyException Hierarchy – Following is the Exception Handling in Java handling hierarchy.
Types of exception in Java
Difference between Checked and Unchecked Exception
Java Exception IndexJava Exception KeywordsException Handling in java is managed via five keywords: try, catch, throw, throws, and finally. Here are 5 keywords that are used in handling exceptions in Java
Java Try-Catch BlockTry-catch syntax: try{ } catch(Exception e){ }
Output:3 5 10 java.lang.ArithmeticException: / by zero
Compile-time error: prog.java:5: error: 'try' without 'catch', 'finally' or resource declarations try{ ^ 1 error
Compile Time Error:prog.java:5: error: 'try' without 'catch', 'finally' or resource declarations try{ ^ prog.java:9: error: 'catch' without 'try' catch(ArithmeticException e){ ^ 2 errorsThings to Remember:Do not keep any code after the statement which is prone to exception. Because if an exception occurred, it will straight away jump to the catch or finally block, ignoring all other statements in the try block. class Main { public static void main (String[] args) { try { System.out.println(4/0); //will not get printed System.out.println("end of try!"); } catch(ArithmeticException e) { System.out.println("divide by 0"); } } }Output:divide by 0
Example: Exact Exception class Main { public static void main (String[] args) { try{ System.out.println(4/0); } //ArithmeticException catch(ArithmeticException e){ System.out.println("divide by 0"); } } }Output: divide by 0Example: Superclass of Exact Exception class Main { public static void main (String[] args) { try{ System.out.println(4/0); } //superclass of ArithmeticException catch(Exception e){ System.out.println("divide by 0"); } } }Output: divide by 0Java Multiple Catch BlockIf you have multiple catches, you have to maintain the hierarchy from subclass to superclass. Incorrect: class Main { public static void main (String[] args) { try{ System.out.println(4/0); }catch(Exception e) { System.out.println("Exception : divide by 0"); }catch(ArithmeticException e) { System.out.println("ArithmeticException :divide by 0"); } } }Compile-time error: prog.java:11: error: exception ArithmeticException has already been caught }catch(ArithmeticException e) ^ 1 errorCorrect: class Main { public static void main (String[] args) { try{ System.out.println(4/0); }catch(ArithmeticException e) { System.out.println("ArithmeticException : divide by 0"); }catch(Exception e) { System.out.println("Exception : divide by 0"); } } }Output: ArithmeticException: Divide by 0Java Nested TryWhen there is another try block within the try block: class Main { public static void main (String[] args) { try{ try{ int[] a={1,2,3}; System.out.println(a[3]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Out of bounds"); } System.out.println(4/0); } catch(ArithmeticException e) { System.out.println("ArithmeticException : divide by 0"); } } }Output: Out of bounds ArithmeticException: Divide by 0Note – If we put code of outer try before inner try, then if an exception occurred, it will ignore the entire inner try and move directly to its catch block. class Main { public static void main (String[] args) { try{ System.out.println(4/0); try{ int[] a={1,2,3}; System.out.println(a[3]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Out of bounds"); } } catch(ArithmeticException e) { System.out.println("ArithmeticException : divide by 0"); } } }Output: ArithmeticException: Divide by 0Java Finally BlockContains code that must be executed no matter if an exception is thrown or not. It contains code of file release, closing connections, etc.
Output: java.lang.ArithmeticException: / by zero finally executed endFinally, will execute even when we do not handle exceptions. Before halting the program, JVM checks if there is a “finally” block. class Main { public static void main (String[] args) { try{ System.out.println(4/0); }finally { System.out.println("cleaning......."); } } }Runtime Error: Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(File.java:4)Output: cleaning.......Java Final vs Finally vs Finalize
Java Throw KeywordIt is a keyword that is used to explicitly throw an exception. We can use throw where according to our logic an exception should occur. Example: public class ExceptionDemo { static void canVote(int age){ if(age<18) try{ throw new Exception(); }catch(Exception e){ System.out.println("you are not an adult!"); } else System.out.println("you can vote!"); } public static void main (String[] args) { canVote(20); canVote(10); } }Output: you can vote! you are not an adult!Java Throws Keyword
Example: public class ExceptionDemo { static void func(int a) throws Exception{ System.out.println(10/a); } public static void main (String[] args) { try{ func(10); func(0); }catch(Exception e){ System.out.println("can't divide by zero"); } } }Output: 1 can't divide by zeroIf callee can throw multiple exceptions, then all will be thrown simultaneously. import java.util.*; public class ExceptionDemo { static void func(int a,int b) throws ArithmeticException, ArrayIndexOutOfBoundsException{ System.out.println(10/a); int[] arr={1,2,3}; System.out.println(arr[b]); } public static void main (String[] args) { Scanner in=new Scanner(System.in); for(int i=0;i<3;i++){ try{ func(in.nextInt(),in.nextInt()); }catch(ArithmeticException e){ System.out.println("can't divide by zero"); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Out of bounds!"); } } } }Input: 2 1 0 1 2 3Output: 5 2 can't divide by zero 5 Out of bounds!Java Throw vs Throws
Java Custom ExceptionYou can create your own exception and give implementation as to how it should behave. Your exception will behave like a child’s class of Exception. Syntax:class YourException extends Exception{}
Implementation: import java.util.*; class WeightLimitExceeded extends Exception{ WeightLimitExceeded(int x){ System.out.print(Math.abs(15-x)+" kg : "); } } class Main { void validWeight(int weight) throws WeightLimitExceeded{ if(weight>15) throw new WeightLimitExceeded(weight); else System.out.println("You are ready to fly!"); } public static void main (String[] args) { Main ob=new Main(); Scanner in=new Scanner(System.in); for(int i=0;i<2;i++){ try{ ob.validWeight(in.nextInt()); }catch(WeightLimitExceeded e){ System.out.println(e); } } } }Input: 20 7Output: 5 kg : WeightLimitExceeded You are ready to fly!Exception Handling in java with method overridingException Handling in Java with Method Overriding is anoverridden method that declares to throw an exception and declare that it can throw the same exception or subtype of that exception. To handle the exception in Java, you will have to follow three important rules. They are depicted in the below figure. Exception Handling in Java with Method OverridingAdvantages and disadvantages of exception handling in javaAdvantages of excepting handling in java
Disadvantages of excepting handling in java
This brings us to the end of this article on exception handling in java. We hope that you are now clear about the concept of exception handling in java. If you wish to know more about the java programming language, then log on to our free java programming course and power ahead in your career. Also Watch: What are the advantages of using an exception handling mechanism in a program?By using exceptions to manage errors, Java programs have the following advantages over traditional error management techniques: Advantage 1: Separating Error Handling Code from "Regular" Code. Advantage 2: Propagating Errors Up the Call Stack. Advantage 3: Grouping Error Types and Error Differentiation.
What is an exception What are the advantages of using exception handling in a program in C++?Exception Handling in C++ is a process to handle runtime errors. We perform exception handling so the normal flow of the application can be maintained even after runtime errors. In C++, exception is an event or object which is thrown at runtime. All exceptions are derived from std::exception class.
What is exception handling and its mechanism?Exception handling is a mechanism that separates code that detects and handles exceptional circumstances from the rest of your program. Note that an exceptional circumstance is not necessarily an error. When a function detects an exceptional situation, you represent this with an object.
What is exception explain exception handling with example?An exception occurs when an unexpected event happens that requires special processing. Examples include a user providing abnormal input, a file system error being encountered when trying to read or write a file, or a program attempting to divide by zero.
|