Java Exception Handling

Introduction to Exception

Most time consuming and tedious task for any programmer is to debug the code, find out the errors and exceptions within it. This is why java itself provides a very helpful mechanism to help programmer deal with most part of it. The mechanism is Exception handling.

In java exception handling mechanism helps us to keep exception handling code separated from the exception generating code. Moreover, exception handling code helps us to deal with variety of exceptions as well.


But before we delve deeper into this course lets learn few things:


What is Exception?

The term Exception indicates exceptional condition. When it occurs in program it alters the normal program flow.


When can Exception occur?

Exception can possibly occur due to hardware failure, resource not found, illogical coding, typo error or others.


What happens when exception occurs?

If your code is not equipped properly with exception handling mechanism to handle any exceptional condition arising for whatsoever reason the normal flow of the program would get disturbed and your application will come up with anomalous behavior.




package exceptionHandling;

public class Unhandled {

      public static void main(String[] args) {

            int a = 15;
            int b = 0;

            int div1 = a/b;
            System.out.println("Result div1:"+ div1);
            int mul = a*b;
            System.out.println("Result div2:"+ mul);



Exception in thread "main" java.lang.ArithmeticException: / by zero

      at exceptionHandling.Unhandled.main(Unhandled.java:9)


In the above code,  int div1 = a/b; results in exception (Arithmetic Exception) since b=0 and any number divided by 0 results in infinity.

Thus our program throws exception and terminates without executing rest of the code.


Note 1:

  • In case Exception is not handled by programmer (like in our case), JVM provides a default exception handler.
  • Default Exception handler prints the exception description, prints the stack trace.
  • Lastly it causes the program to terminate.


Note 2:

  • If your code is properly equipped with exception handling mechanism, then the arising exception will be caught instantly and will be dealt in a proper way so that it doesn’t impact the normal flow of the code. We will be learning it new next few chapters.

Please Share this page
Views : 392
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!