top of page
Writer's picturePushp Raj

Exception Handling in Java with Examples

Updated: May 25, 2023


Exception Handling in Java with Examples
Exception Handling in Java with Examples


What exactly are Java Annotations?


Java annotations are used to provide additional or supplementary information about a program. Annotations are used in Java to provide additional information about a program.


● Annotations in Java begin with '@'.

● An ordered program's activity is unaffected by Java annotations.

● Annotations in Java aid in connecting metadata (data) to program components such as case factors, constructors, strategies, classes, etc.

● Annotations in Java are not merely comments since they can alter how the compiler handles a program. For example, look at the code below.


Example:

class Base

{

public void display()

{

System.out.println("Base display()");

}

}

class Derived extends Base

{

@Override

public void display(int x)

{

System.out.println("Derived display(int )");

}

public static void main(String args[])

{

Derived obj = new Derived();

obj.display();

}

}


Java Annotation Categories


In Java, there are three types of annotations.


  1. Marker Annotation


The fundamental idea is to create an annotation in Java. These Java annotations do not contain any individuals or information. In this regard, its quality as a comment is adequate. Because the marker interface has no individuals, determining if it is available is sufficient. Marker Annotation is used in the case of @Override.


Example: @TestingAnnotation()


  1. Single Java Value Annotations


These annotations contain only one part and allow for a quick method of calculating the part's estimation. When the comment is connected, we only need to mention the incentive for that portion and do not need to determine the name of the part. However, the part's name must be valued to use this shorthand.


  1. Full Jaga Annotation


They have many values, pairs, data members, and so forth.


Example:- @TestingAnnotation(owner=”Data”, value=”Class Schools”)


Predefined/ Standard Annotations in Java


In Java, there are seven built-in annotations.


The four imported from Java.lang.annotation are as follows:


● @Retention

● @Documented

● @Target

● @Inherited


The three in Java.lang are as follows:


● @Deprecated

● @Override

● @SuppressWarnings


  1. @Deprecated Annotation


● @ Deprecated Java Annotation indicates that an old declaration has been replaced with a newer one; thus, it is a marker annotation.

● The Javadoc @deprecated tag should be used when a component has been deployed.

● A @deprecated tag is used for documentation, while a @deprecated annotation is used for runtime reflection.

● When both regions are used, a @deprecated tag is more important than a @deprecated annotation.


Example:


public class DeprecatedTest

{

@Deprecated

public void Display()

{

System.out.println("Deprecatedtest display()");

}

public static void main(String args[])

{

DeprecatedTest d1 = new DeprecatedTest();

d1.Display();

}

}


  1. @Override Annotation


@Override Java Annotations are a type of marker annotation that can only be used on one strategy. A strategy clarified with @Override must take precedence over a strategy from a superclass. If it does not, an order time error will occur (for example, see this). It ensures that a superclass technique is indeed surpassed and not simply overloaded.


class yest

{

public void Display()

{

System.out.println("Base display()");

}

public static void main(String args[])

{

Base t1 = new Derived();

t1.Display();

}

}

class Derived extends yest

{

@Override

public void Display()

{

System.out.println("Derived display is the output()");

}

}


Output:


Derived displays is the output


  1. @SuppressWarnings Annotation


These Java Annotations instruct the compiler to suppress specified compiler notices. The names of the warnings are indicated in a string structure. This type of annotation can be linked to a statement.


There are two types of Java warning messages. They are unchecked depreciation. When inheritance code interacts with code that uses generics, any unchecked cautioning is generated.


Example:


class DeprecatedTest

{

@Deprecated

public void Display()

{

System.out.println("Deprecatedtest displaying in Java");

}

}

public class SuppressWarningTest

{

@SuppressWarnings({"checked", "deprecation"})

public static void main(String args[])

{

DeprecatedTest d1 = new DeprecatedTest();

d1.Display();

}

}


Output


Deprecatedtest displaying in Java


  1. @Documented Annotations


A marker interface informs a machine that an explanation is to be archived. Javadoc remarks omit Java annotations. Using the @Documented remark in the code allows devices like Javadoc to parse it and include the explanatory compose data in the generated archive.


  1. Targeted Annotations


It is only meant to be used as an explanation for another annotation. @Target accepts one argument, which must match the ElementType count. This annotation specifies the kind of assertions that Java annotations can relate to. The constants are listed below, along with the type of affirmation they apply.


Target Constant


Java Annotations Can be Applied To

ANNOTATION_TYPE


Another annotation


CONSTRUCTOR


Constructor

FIELD


Field


LOCAL_VARIABLE


Local variable


METHOD


Method


PACKAGE


Package


PARAMETER


Parameter


TYPE


Class, Interface, or enumeration

In a @Targetannotation, we can identify at least one of these characteristics. To calculate various values, we should include them in the props delimited rundown. For example, to indicate that an annotation only applies to fields and neighborhood factors, use the @Target comment: @Target(ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.LOCAL_VARIABLE) Annotation for Retention It determines where and to what extent the statement is retentive. The three values that the @Retention explanation can have are:


SOURCE: Java Annotations will be retained at the source level and ignored by the compiler.

CLASS: Annotations will be ignored by the JVM at order time.

RUNTIME: These will be held during runtime.

  1. @Inherited Annotations


@Inherited Java annotations are marker annotations that can be used only after annotation confirmation. It only has an impact on the explanations that will be used for class presentations. @Inherited adds a comment to a superclass that is acquired by a subclass. In this manner, when a demand for a specific remark is made to the subclass, the subclass is checked if the comment is missing in the subclass. That comment will be returned if the comment is available in the superclass and is explained with @Inherited.


  1. User-defined/ Custom Annotations


Client-defined Java explanations can clarify program components such as factors, constructors, approaches, etc. These explanations can be connected just before a component's statement (constructor, strategy, classes, and so on).


Syntax:


[Access Specifier] @interface<AnnotationName>

{

DataType <Method Name>() [default value];

}

● AnnotationName serves as an identifier.

● The parameter should not be related to strategy assertions, and the tossing provision should not be used with technique disclosure.

● Although parameters will not have an invalid esteem, they may have a default esteem.

● The default esteem is optional.

● The return strategy should be either crude, enum, string, or class name, or an exhibit of crude, enum, string, or class name write.

Example:

import java.lang.annotation.Documented;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

@Documented

@Retention(RetentionPolicy.RUNTIME)

@ interface TestAnnotation

{

String Developer() default "Rahul";

String Expirydate();

}

public class Test

{

@TestAnnotation(Developer="data", Expirydate="08-11-2022")

void fun1()

{

System.out.println("Test method 1");

}

@TestAnnotation(Developer="class", Expirydate="08-11-2022")

void fun2()

{

System.out.println("Test method 2");

}

public static void main(String args[])

{

System.out.println("Cipherschools");

}

}

Output:

Cipherschools


What are Java Exceptions?


We understand that exceptions are aberrant conditions that do not occur daily. Exceptions in Java programming are events that disrupt the normal flow of a program. It is a type of object thrown during runtime.


Exception Cause in Java


An exception can occur for a variety of reasons. Among the most common sources of exceptions are:


● By the user during an input procedure.

● The programmer's syntax.

● Due to a shortage of resources, like insufficient RAM.


Java exception Categories


In Java, there are two types of exceptions. They are as follows:


  1. JVM exceptions: These are exceptions and errors thrown solely by the JVM. NullPointerException, ArrayIndexOutOfBoundsException, and ClassCastException are other examples.

  2. Programmatic Exceptions: These are exceptions explicitly thrown by the application or API developer. IllegalArgumentException and IllegalStateException are two examples.


Java Exception Hierarchy


Exceptions are defined in Java by Java.lang—throwable class. The class is inherited by two subclasses, Exception, and Error, which are inherited by other subclasses.


Java Exception Types


There are two kinds of exceptions. There are two sorts of oddities, checked and unchecked, but according to Oracle, there are three:


  1. Exception Exception

  2. Unchecked Exception

  3. Error



The distinction between Java Checked Exceptions, Unchecked Exceptions, and Errors.


The distinction between Java Checked Exceptions, Unchecked Exceptions, and Errors is as follows:


Checked Exception in Java: Exceptions are exception classes that directly inherit from the Throwable class with the exceptions of RuntimeException and Error. They are validated during the compilation process—for instance, IOException, SQLException, ClassNotFound, etc.

Unchecked Exception in Java: Unchecked exceptions derive from the RuntimeException class. They are tested during runtime rather than compilation—for instance, ArithmeticException, IndexOutOfBOundException, etc.

Error in Java: Errors are unrecoverable exceptions. They are also checked during execution. OutOfMemoryError, VirtualMachineError, and so forth.


JVM Exception Handling (Default Exception Handling)


If an exception occurs within the method, the Exception Object is created. The object is subsequently passed to the runtime system, sometimes called the JVM. The object holds all of the exception's information, beginning with the name and description of the exception and ending with the exception's current state. The Call Stack is an ordered list of the methods that may be invoked when the exception occurs.


Following that, the following will occur:


● The JVM scans the call stack for the method containing the code to handle the encountered exception; this code block is known as an Exception handler.

● The JVM now searches for the method where the exception occurred.

● If the JVM identifies a good handler, the exception method is passed to the handler.

● If the JVM cannot locate an appropriate handler, the object is passed to the default exception handler, which prints a default message and terminates the abnormality.


Code to demonstrate JVM exception handling:


package com.DataFlair.exceptions;

public class exception

{

public static void main(String args[]){

String str = null;

System.out.println(str.length());

}

}


Output:

java.lang.NullPointerException

at com.Cipherschools.exceptions.exception.main(exception.java:7)

at com.Cipherschools.exceptions.__SHELL0.run(__SHELL0.java:6)

at Java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at Java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at Java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.base/java.lang.reflect.Method.invoke(Method.java:566)

at bluej. runtime.ExecServer$3.lambda$run$0(ExecServer.java:849)

at bluej. runtime.ExecServer.runOnTargetThread(ExecServer.java:964)

at bluej. runtime.ExecServer$3.run(ExecServer.java:846)


Java Exception Handling


Developers can Exceptions in Java can be handled within the program using exception handling. Runtime exceptions such as IOExceptions, ArithmeticExceptions, and so on can be handled via exception handling.


Exception Methods in Java


SL. No.


Method


Description

public String getMessage()

This method returns a string message that describes the error that happened.

public Throwable getCause()

This method throws the exception that caused it.


public String toString()

This function returns the message of the getMessage() method as well as the exception class concatenated to it.


public void printStackTrace()

This function delivers the toString() method's output and stack trace.


public StackTraceElement [] getStackTrace()

This method returns an array comprising all of the stack trace's elements.


Benefits of using Java Exception Handling:


The following are the benefits of using Java Exception Handling:


We can maintain the program's normal flow by using exception handling. Exceptions, as we've seen before, break the usual flow of a program. Thus, exception handling skips the exception without interfering with the program's execution.


Important Java Exception Handling Keywords Include:


  1. try: The try block is where the code that has to be checked for exceptions is located. A catch or finally block must follow the try block; it cannot be used independently.

  2. catch: We can catch the exception thrown by the try block using the catch block. It is declared following the try block.

  3. finally: We can run an essential piece of code using the finally block since the final block will be executed regardless of the outcome of the try block.

  4. throw: We can use the throw keyword to throw a preset exception.

  5. throws: We can declare a new exception from the exception classes with the throws keyword.


Below is an example of a program that uses the try-catch block to handle exceptions:

package com.CipherSchools.exceptions;


public class exceptionhandling

{

public static void main(String[] args) {

try {

char[] ch = {'C', 'I', 'P', 'H', 'E', 'R', 'S', 'C', 'H', 'O', 'O', 'L', 'S'};

System.out.println(ch[10]);

} catch (Exception e) {

System.out.println("Something went wrong while indexing of Array");

} finally {

System.out.println("The 'try catch' is over, continuing the program from here!");

}

}

}

Output

Something went wrong while indexing of Array

The 'try catch' is over, continuing the program from here!


User-defined or customized Exception in Java


Not all exceptions are defined in the JVM; in some cases, the programmer may need to define their exception.

To accomplish this, Java allows you to build a customized exception.


Rules for creating a Java Exception


The following are the rules for producing a Java Exception:

● To generate a customized Java exception, keep the following points in mind:

● The custom exception class should extend the built-in Exception class.

● The user must override the toString() method in the user-defined exception class.


Creating a user-defined Exception class using the following code


package com.CipherSchools.exceptions;

public class UserDefException extends Exception

{

private static int year;

public UserDefException(int year)

{

this.year=year;

}

public String toString()

{

return "Age below 18, Underaged!!!";

}

public static void main(String args[]) throws Exception

{

UserDefException obj = new UserDefException( 2005 );

if(year > 2003)

{

throw new UserDefException(year);

}

else

{

System.out.println("Entered year is: " +year);

}

}

}


Output:

Age below 18, Underaged!!!

At com.CipherSchools.exceptions.UserDefException.main(UserDefException.java:18)

at com.CipherSchools.exceptions.__SHELL0.run(__SHELL0.java:6)

at Java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at Java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at Java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.base/java.lang.reflect.Method.invoke(Method.java:566)

at bluej. runtime.ExecServer$3.lambda$run$0(ExecServer.java:849)

at bluej. runtime.ExecServer.runOnTargetThread(ExecServer.java:964)

at bluej. runtime.ExecServer$3.run(ExecServer.java:846)

As a result, we can observe that the program throws an exception that we produced rather than an intrinsic exception. This is handy for checking user input against specific criteria.


Essential Things to Keep in Mind


● More than one statement in a function can throw an exception. Each statement requires its try-catch block.

● An exception handler handles each exception. A catch block is required to correlate an exception handler with an exception.

● A try block can have from 0 to n catch blocks, but only one finally block.

● A finally block is optional; it executes regardless of the try block's output.

● Lastly, A try block must be followed by either a catch or a finally block.


Conclusion


Finally, exceptions and annotations are significant Java features that play an essential role in improving the robustness, flexibility, and maintainability of Java programming.


Exceptions enable developers to manage runtime mistakes gracefully, improving Java applications' dependability and fault tolerance. Developers can manage unforeseen events, offer relevant error messages to users, and prevent crashes or data corruption by catching and handling exceptions.


On the other hand, annotations give metadata that can be used to add extra information to Java code, such as compiler, tool, or framework instructions. Developers can use annotations to improve Java code's readability, maintainability, and performance by adding context or behavior.


Exceptions and annotations are both essential components of modern Java programming and mastering their use can significantly enhance Java code quality. Handling exceptions correctly and utilizing annotations can result in more resilient, efficient, and maintainable Java applications.


In conclusion, exceptions and annotations are powerful Java features that help developers design dependable, adaptable, and maintainable code. Understanding how to use exceptions and annotations effectively is critical for Java developers who want to create high-quality software that meets the demands of modern software development.


20 views

Comments


Subscribe to Our Newsletter

Thanks for submitting!

bottom of page