0%
Loading ...

Java Exception Handling

This tutorial category contains all the tutorials related to java exception handling.

Custom Exception in Java

In this tutorial, we will learn about Custom Exception in Java. Custom Exceptions are also known as a user-defined exception. The main motive of creating a custom exception is to create a new exception according to project requirement. When you create a custom exception you have to inherit Exception class as a parent in your custom exception class. please check out the following example. Example Program: //creating an custom Exception class class MyCustomException extends Exception{ public MyCustomException(){ System.out.println(“Constucor of MyCustomException invoked”); } public String getMessage() { return “Hello, This is getMessage() in MyCustomException”; } } public class Example{ public static void main(String args[]){ try{ System.out.println(“In try block”); throw new MyCustomException(); //throwing exception explicitly }catch(MyCustomException e){ System.out.println(e.getMessage()); System.out.println(“In catch block”); } } } Output: In try block Constucor of MyCustomException invoked Hello, This is getMessage() in MyCustomException In catch block   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Custom Exception in Java Read More »

Throw keyword in Java

In this tutorial, we will learn about throw keyword in Java. The throw keyword in java is used to throw an exception explicitly. We can throw both kinds of checked and unchecked exceptions using this throw keyword. But we mainly use throw keyword to throw custom exceptions(also known as the user-defined exceptions). Check out the following syntax of throw keyword. throw objectOfExceptionClass; As in above syntax you can see to throw an exception first of all we have to write throw keyword then object of Exception class. Please check out the following example program. Example Program: public class Example { public static void main(String args[]) { try { System.out.println(“In try block”); throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println(“In catch block”); } } } Output: In try block In catch block   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Throw keyword in Java Read More »

Throws keyword in Java

In this tutorial, we will learn throws keyword in Java. There are many time when compiler finds some suspicious code that might throw a checked exception and warn programmers to solve exceptions. If programmer will not handle this kind of exceptions then the compiler will throw an error while compiling unreported exception XXX must be caught or declared to be thrown. In this kind of situation, we have two options whether to use a try-catch block to handle the exception or use throw keyword. The throw keyword works in a simple way when we write it with our suspicious code it means we will not handle this exception the caller of this function will solve the exception. If our code is in the main function then JVM will handle that exception. Check out the following example program. Example Program: public class Example { public static void main(String[] args) { Thread.sleep(100); // a checked exception System.out.println(“Owlbuddy”); } } Output: Example.java:5: error: unreported exception InterruptedException; must be caught or declared to be thrown Thread.sleep(10000); // a checked exception ^ 1 error Do not worry In case you don’t know what is Thread. You will get detail tutorials of Multi-Threading in upcoming tutorials. In above we have a checked exception that’s why our code is not compiling. Here we will rewrite the same code again what this time we will use throws keyword to solve this Exception. Example Program: public class Example { public static void main(String[] args) throws InterruptedException { Thread.sleep(100); // a checked exception System.out.println(“Owlbuddy”); } } Output: Owlbuddy Here is a question for you, do you know in the above example who is responsible for handling InterruptedException. If your answer is JVM then it’s right. Because here exception inside the main method. It is important to note that using throws keyword we are not handling any exception we are just delegating the responsibility of exception handling to the caller.  Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Throws keyword in Java Read More »

Try Catch block in Java

In this tutorial, we will learn about Try Catch Block in Java. Using Try Catch block is the best way to handle exceptions in Java. We keep all the code that might throw an exception in the try block. The try block is followed by the catch and finally blocks. In this catch and finally blocks, we write code to handle the exception. try{ //Here is code that may throw an exception }catch(Exception_Class ref){ } Before going further, here we write a code(with exception) without Try Catch block: Example Program(without Try Catch Block) public class Example{ public static void main(String args[]){ System.out.println(“Ans of 10/2 =”+(10/2)); System.out.println(“Ans of 12/3 =”+(12/3)); System.out.println(“Ans of 5/0 =”+(5/0)); System.out.println(“Ans of 24/6 =”+(24/6)); System.out.println(“Ans of 8/2 =”+(8/2)); } } Output: Ans of 10/2 =5 Ans of 10/2 =4 Exception in thread “main” java.lang.ArithmeticException: / by zero at Example.main(Example.java:5)} As you can see in the above example program we got an ArithmeticException(Because we can’t divide a number by zero in Java) on the fifth line. Now in the next example, we will write the same program but with the Try-Catch block to handle the Arithmetic Exception we got in our last example. Example Program(With Try-Catch): public class Example{ public static void main(String args[]){ System.out.println(“Ans of 10/2 =”+(10/2)); System.out.println(“Ans of 12/3 =”+(12/3)); try{ System.out.println(“Ans of 5/0 =”+(5/0)); }catch(ArithmeticException e){ System.out.println(e.getMessage()); } System.out.println(“Ans of 24/6 =”+(24/6)); System.out.println(“Ans of 8/2 =”+(8/2)); } } Output: Ans of 10/2 =5 Ans of 12/3 =4 / by zero Ans of 24/6 =4 Ans of 8/2 =4 Here you can see how we handled ArithmeticException in our last example using try catch block. In the try block, we placed all the code which might throw an exception and we catch this exception using catch block. Instead of adding particular exception class such as ArithmeticException or ArrayIndexOutOfBoundsException you can directly add parent Exception class. Example Program: public class Example{ public static void main(String args[]){ System.out.println(“Ans of 10/2 =”+(10/2)); System.out.println(“Ans of 12/3 =”+(12/3)); try{ System.out.println(“Ans of 5/0 =”+(5/0)); }catch(Exception e){ System.out.println(e.getMessage()); } System.out.println(“Ans of 24/6 =”+(24/6)); System.out.println(“Ans of 8/2 =”+(8/2)); } } Output: Ans of 10/2 =5 Ans of 12/3 =4 / by zero Ans of 24/6 =4 Ans of 8/2 =4 Multiple catch blocks: In many situations, your code might throw multiple types of exception so to solve different kind of exception we can add multiple catch block with a try block. Check out the following example. Example Program: public class Example{ public static void main(String args[]){ try{ int num[]=new int[5]; num[4]=10/0; System.out.println(“Done”); } catch(ArithmeticException e){ System.out.println(“Can not divide by Zero”); } catch(ArrayIndexOutOfBoundsException e){ System.out.println(“Out of Array Index”); } System.out.println(“Outside try-catch block”); System.out.println(“Outside try-catch block”); } } Output: Can not divide by Zero Outside try-catch block Outside try-catch block As in the above example, you can see we have added multiple catch blocks(ArithmeticException and ArrayIndexOutOfBoundsException) and in the above example, we are got handled ArithmeticException. Here is the same example again with little change to show you the concept of multiple catch blocks. Example Program: public class Example{ public static void main(String args[]){ try{ int num[]=new int[5]; num[6]=10/2; System.out.println(“Done”); } catch(ArithmeticException e){ System.out.println(“Can not divide by Zero”); } catch(ArrayIndexOutOfBoundsException e){ System.out.println(“Out of Array Index”); } System.out.println(“Outside try-catch block”); System.out.println(“Outside try-catch block”); } } Output: Out of Array Index Outside try-catch block Outside try-catch block Please note, if you want to add multiple catch blocks with try block then always add parent Exception class in the last catch block. Example Program: public class Example{ public static void main(String args[]){ try{ int num[]; num[6]=10/2; System.out.println(“Done”); } catch(ArithmeticException e){ System.out.println(“Can not divide by Zero”); } catch(ArrayIndexOutOfBoundsException e){ System.out.println(“Out of Array Index”); } catch(Exception e){ System.out.println(“Exception in Code”); } System.out.println(“Outside try-catch block”); System.out.println(“Outside try-catch block”); } } Finally Block in Java: We can add finally block at the end of all the catch blocks. Finally block is mainly used to hold cleanup code such as you can code to close a database connection. The important thing to note about finally block is the code inside the finally both runs in both situation whether exception occur or not. Please check out the following example. public class Example{ public static void main(String args[]){ try{ int num[]=new int[5]; num[3]=10/2; System.out.println(“Done”); } catch(ArithmeticException e){ System.out.println(“Can not divide by Zero”); } catch(ArrayIndexOutOfBoundsException e){ System.out.println(“Out of Array Index”); } finally{ System.out.println(“This is finally block”); } System.out.println(“Outside try-catch block”); System.out.println(“Outside try-catch block”); } } Output: Done This is finally block Outside try-catch block Outside try-catch block   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Try Catch block in Java Read More »

Exception Handling in Java

In this tutorial, we will learn about an Introduction to Exception Handling in Java. According to the dictionary, the word exception means abnormal and Here Exception handling means to solve abnormal situations which occur while the execution of code. During the execution of the program due to several reasons such as wrong input, or some programming mistakes, the program stops working and throw an error on screen which is known exception. Java has a concept called Exception Handling to handle these exceptions. Example Program: public class Example{ public static void main(String args[]){ System.out.println(“Ans of 10/2 =”+(10/2)); System.out.println(“Ans of 12/3 =”+(12/3)); System.out.println(“Ans of 5/0 =”+(5/0)); System.out.println(“Ans of 24/6 =”+(24/6)); System.out.println(“Ans of 8/2 =”+(8/2)); } } Output: Ans of 10/2 =5 Ans of 10/2 =4 Exception in thread “main” java.lang.ArithmeticException: / by zero at Example.main(Example.java:5)} As in the above example, you can see our code was working perfectly till the 4th line. But when it reached to 5th line and we tried to divide 5 by 0. We got an exception(In Java / by Zero is an Exception) and our program stropped to working immediately as two can see there were two more lines(line number 6th and 7th) which were not executed because of Exception. In java, there are various inbuilt classes available in Java Standard Library which helps us to work with exception class. The parent class of all the exception class is java.lang.Exception Class Types of Exception: Java has two kinds of exception which an occur in Java programs. Types of Exception are as follow: Checked Exception Unchecked Exception Checked Exception: The checked exceptions are those exceptions which can be caught on compilation time by the compiler. These kinds of exceptions can not be ignored by the compiler. The programmer has to solve these exceptions first to run the program(without solving these checked exceptions program would not compile). List of Checked Exceptions in Java: ClassNotFoundException NoSuchFieldException NoSuchMethodException InterruptedException IOException InvalidClassException SQLException any many more… Example Program of Checked Exception in Java: import java.io.File; import java.io.FileReader; public class Example{ public static void main(String args[]) { File file = new File(“c://myfile.txt”); FileReader fileReader = new FileReader(file); } Output: Example.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader fileReader = new FileReader(file); Unchecked Exception: Unchecked Exceptions are those exceptions which can not be caught at the time of compilation of code. These exceptions only occur while the execution of code and stops the code from working. Example Program of Unchecked Exception in Java: public class Example { static String names[]={“ABC”,”XYZ”,”MNO”}; public static void main(String args[]) { System.out.println(names[5]); } } Output: Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5 at Example.main(Example.java:4) List of Unhecked Exceptions in Java: ArithmeticException ArrayIndexOutOfBoundsException EnumConstantNotPresentException NegativeArraySizeException NumberFormatException NullPointerException IllegalStateException UnsupportedOperationException and many more.. Exception Class Hierarchy: The exception classes which we saw in list of checked and unchecked Exception classes are child classes of Exception class. Here is illustration to show hierarchy of all these exception classes. Please continue with next tutorial the next tutorial we will learn how to handle exception in java using try catch block. Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Exception Handling in Java Read More »

Scroll to Top
×