Named exceptions in java

User defined and custom exceptions in Java

An exception is an issue (run time error) that occurred during the execution of a program. For understanding purpose let us look at it in a different manner.

Generally, when you compile a program, if it gets compiled without a .class file will be created, this is the executable file in Java, and every time you execute this .class file it is supposed to run successfully executing each line in the program without any issues. But, in some exceptional cases, while executing the program, JVM encounters some ambiguous scenarios where it doesn’t know what to do.

Here are some example scenarios −

  • If you have an array of size 10 if a line in your code tries to access the 11th element in this array.
  • If you are trying to divide a number with 0 which (results to infinity and JVM doesn’t understand how to evaluate it).

Such cases are known as exceptions when an exception occurs the program gets terminated abnormally. Certain exceptions are prompted at compile time they are known as checked exceptions or, compile-time exceptions and, exceptions that occur at run-time are known as run time exceptions or, unchecked exceptions.

Each possible exception is represented by a predefined class and all these classes are found in the java.lang package. Following are some exception classes

NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, IllegalArgumentException, IllegalStateException etc…

Example: ArithmeticException

import java.util.Scanner; public class ExceptionExample < public static void main(String args[]) < Scanner sc = new Scanner(System.in); System.out.println("Enter first number: "); int a = sc.nextInt(); System.out.println("Enter second number: "); int b = sc.nextInt(); int c = a/b; System.out.println("The result is: "+c); >>

Output

Enter first number: 100 Enter second number: 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionExample.main(ExceptionExample.java:10)

Example: ArrayIndexOutOfBoundsException

import java.util.Arrays; import java.util.Scanner; public class AIOBSample < public static void main(String args[])< int[] myArray = ; System.out.println("Elements in the array are: "); System.out.println(Arrays.toString(myArray)); Scanner sc = new Scanner(System.in); System.out.println("Enter the index of the required element: "); int element = sc.nextInt(); System.out.println("Element in the given index is :: "+myArray[element]); > >

Output

Run time exception −

Elements in the array are: [897, 56, 78, 90, 12, 123, 75] Enter the index of the required element: 7 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at AIOBSample.main(AIOBSample.java:12)

Example: ArrayStoreException

import java.util.Arrays; public class ArrayStoreExceptionExample < public static void main(String args[]) < Number integerArray[] = new Integer[3]; integerArray[0] = 12548; integerArray[1] = 36987; integerArray[2] = 555.50; integerArray[3] = 12548; System.out.println(Arrays.toString(integerArray)); >>

Output

Runtime Exception −

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Double at ther.ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:9)

Example: NoSuchElementException

import java.util.Enumeration; import java.util.Vector; public class EnumExample < public static void main(String args[]) < //instantiating a Vector Vectorvec = new Vector( ); //Populating the vector vec.add(1254); vec.add(4587); //Retrieving the elements using the Enumeration Enumeration en = vec.elements(); System.out.println(en.nextElement()); System.out.println(en.nextElement()); //Retrieving the next element after reaching the end System.out.println(en.nextElement()); > >

Output

Runtime Exception −

1254 4587 Exception in thread "main" java.util.NoSuchElementException: Vector Enumeration at java.util.Vector$1.nextElement(Unknown Source) at July_set2.EnumExample.main(EnumExample.java:18)

User-defined exceptions

You can create your own exceptions in Java and they are known as user-defined exceptions or custom exceptions.

Читайте также:  Http stat50120 mkstat ru index html 3252

To create a user-defined exception extend one of the above-mentioned classes. To display the message override the toString() method or, call the superclass parameterized constructor bypassing the message in String format.

MyException(String msg) < super(msg); >Or, public String toString()

Then, in other classes wherever you need this exception to be raised, create an object of the created custom exception class and, throw the exception using the throw keyword.

MyException ex = new MyException (); If(condition……….)

Custom Checked and Custom Unchecked

  • All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • If you want to write a runtime exception, you need to extend the RuntimeException class.

Example: Custom Checked exception

Following Java program Demonstrates how to create a Custom checked exception.

import java.util.Scanner; class NotProperNameException extends Exception < NotProperNameException(String msg)< super(msg); >> public class CustomCheckedException< private String name; private int age; public static boolean containsAlphabet(String name) < for (int i = 0; i < name.length(); i++) < char ch = name.charAt(i); if (!(ch >= 'a' && ch > return true; > public CustomCheckedException(String name, int age) < if(!containsAlphabet(name)&&name!=null) < String msg = "Improper name (Should contain only characters between a to z (all small))"; NotProperNameException exName = new NotProperNameException(msg); throw exName; >this.name = name; this.age = age; > public void display() < System.out.println("Name of the Student: "+this.name ); System.out.println("Age of the Student: "+this.age ); >public static void main(String args[]) < Scanner sc= new Scanner(System.in); System.out.println("Enter the name of the person: "); String name = sc.next(); System.out.println("Enter the age of the person: "); int age = sc.nextInt(); CustomCheckedException obj = new CustomCheckedException(name, age); obj.display(); >>

Output

Compile-time exception

On compiling, the above program generates the following exception.

CustomCheckedException.java:24: error: unreported exception NotProperNameException; must be caught or declared to be thrown throw exName; ^ 1 error

Example: Custom unChecked exception

If you simply change the class that your custom exception inherits to RuntimeException it will be thrown at run time

class NotProperNameException extends RuntimeException < NotProperNameException(String msg)< super(msg); >>

If you run the previous program By replacing the NotProperNameException class with the above piece of code and run it, it generates the following runtime exception.

Читайте также:  In arrayloader php line 44

Output

Runtime exception

Enter the name of the person: Krishna1234 Enter the age of the person: 20 Exception in thread "main" july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small)) at july_set3.CustomCheckedException.(CustomCheckedException.java:25) at july_set3.CustomCheckedException.main(CustomCheckedException.java:41)

Источник

Named exceptions in java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

Named exceptions in java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java
Читайте также:  Sum from to python

Источник

Оцените статью