Error code handling in java

Java Exception Handling — Exception Handling in Java

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Exception Handling is a mechanism to handle runtime errors. In this Exception Handling in Java or Java Exceptions with checked, unchecked and errors with example and usage of try, catch, throw, throws and finally keywords. If an exception occurs within the try block that exception can be handled in catch block. Any exception that is thrown out of a method must be specified by a throws clause. Any code that absolutely must be executed after a try block must be put it in the finally block.

What is an Exception ?

An exception is an unwanted or unexpected event, which occurs during the execution of a program at run time, that disrupts the normal flow of the program execution. Java exception handling is managed by try, catch, throw, throws, and finally. If an exception occurs within the try block that exception can be handled in catch block. Any exception that is thrown out of a method must be specified by a throws clause. Any code that absolutely must be executed after a try block must be put it in the finally block.

  • Error that occurs during runtime
  • Exceptional event
  • Cause normal program flow to be disrupted

Java Exception Handling - Exception Handling in Java, Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Exception Handling is a mechanism to handle runtime errors., Complete Tutorial on Exception Handling in Java, Best Java Exception Handling Tutorial

Types of Exception in Java

Checked Exception

The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions. Checked exceptions are checked at compile time. Checked Exceptions are IOException, SQLException etc.

Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions. Unchecked exceptions are not checked at compile time, but they are checked at runtime. Unchecked Exceptions are ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

What are the keywords used in exception handling ?

There are five keywords used in Java exception.

List of five exception handling keywords in Java are as follows.

Exception Handling keywords in Java

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. The brief description of Java Exception Handling keywords are as follows.

Читайте также:  Php cgi exe exited unexpectedly

Java Exception Handling Keywords and Their Description

Java try keyword

The try keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can’t use try block alone.

Java catch keyword

The catch block is used to handle the exception. It must be preceded by try block which means we can’t use catch block alone. It can be followed by finally block later.

Java finally keyword

The finally block is used to execute the important code of the program. It is executed whether an exception is handled or not.
A finally keyword is used to create a block of code that follows a try block. A finally block of code is always executed whether an exception has occurred or not.

Java throw keyword» >throw Keyword

The throw keyword is used to throw an exception.
throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown.
Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled. A method can do so by using the throws keyword.

Java throws keyword

The throws keyword is used to declare exceptions. It doesn’t throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.
Throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.

What is the difference between throw and throws ?

Following are the difference between throw and throws keywords .

throw throws
throw keyword is used to throw an exception explicitly. throws keyword is used to declare an exception possible during its execution.
throw keyword is followed by an instance of Throwable class or one of its sub-classes. throws keyword is followed by one or more Exception class names separated by commas.
throw keyword is declared inside a method body. throws keyword is used with method signature (method declaration).
We cannot throw multiple exceptions using throw keyword. We can declare multiple exceptions (separated by commas) using throws keyword.

Java Exception Examples

  1. Divide by zero errors
  2. Accessing the elements of an array beyond its range
  3. Invalid input
  4. Hard disk crash
  5. Opening a non-existent file
  6. Heap memory exhausted

Java Exception Example

/* Java Exception Example Save with file name ExceptionExample1.java */ public class ExceptionExample1 < public static void main(String args[]) < System.out.println(3/0); System.out.println("No Exception Occurred"); >>

The default exception handler provided by java runtime will prints out the exception description, stack trace (Hierarchy of methods where the exception occurred) and Causes the program to terminate. The Exception message looks like the following message.

Exception in thread «main» java.lang.ArithmeticException: / by zero
at ExceptionExample1.main (ExceptionExample1.java:8)

What Happens When an Exception Occurs ?

  1. When an exception occurs within a method, the method creates an exception object and hands it off to the runtime system.
  2. The runtime system searches the call stack for a method that contains an exception handler
  3. When an appropriate handler is found, the runtime system passes the exception to the handler
  4. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, the runtime system (and, consequently, the program) terminates and uses the default exception handler
Читайте также:  Php framework user authentication

Benefits of Java Exception Handling

  1. Separating Error-Handling code from regular business logic code
  2. Propagating errors up the call stack
  3. Grouping and differentiating error types

Separating Error Handling Code from Regular Code

Exceptions enable you to write the main flow of your code and to deal with the exceptional cases elsewhere. Note that exceptions don’t spare you the effort of doing the work of detecting, reporting, and handling errors, but they do help you organize the work more effectively.

Catching Exceptions in Java with try catch

Java Exception Handling Example

In the following Java Exception Handling Example where we using a try catch statement to handle the exception.

Exception Handling in Java Example with try catch

/* Catching Exceptions in Java with try catch Example Save with file name ExceptionExample2.java */ public class ExceptionExample2 < public static void main(String args[]) < try < System.out.println(3/0); System.out.println("No Exception Occurred"); >catch(ArithmeticException ae) < System.out.println(ae); >> >

Catching Exceptions in Java with multiple catch

Before Java 7, we used to catch multiple exceptions one by one as shown below. Multiple catches should be ordered from subclass to super class. If a catch block handles multiple exceptions in Java 7, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can’t change it. The byte code generated by this feature is smaller and reduce code redundancy. In Java 7, we can catch both these exceptions in a single catch block as follows.

catch(IOException | SQLException ex)

Catching Exceptions in Java with multiple catch

/* Catching Exceptions in Java with multiple catch Example Save with file name ExceptionExample3.java */ public class ExceptionExample3 < public static void main(String args[]) < try < int nos[] = new int[7]; // throw ArrayIndexOutOfBoundsException exception nos[10] = 777; System.out.println(3/0); System.out.println("No Exception Occurred"); >catch(ArithmeticException ae) < System.out.println("Arithmetic Exception : "+ae); >catch(ArrayIndexOutOfBoundsException arre) < System.out.println("ArrayIndexOutOfBoundsException : "+arre); >> >

Nested Exception Handling in Java

/* Nested Exception Handling in Java Example Save with file name ExceptionExample4.java */ public class ExceptionExample4 < public static void main(String args[]) < try < try < int nos[] = new int[7]; //throw ArrayIndexOutOfBoundsException exception nos[10] = 777; >catch(ArrayIndexOutOfBoundsException arre) < System.out.println("Arithmetic Exception : "+arre); >System.out.println("No Exception Occurred in outer try-block"); > catch(Exception ex) < System.out.println("Some other Exception : "+ex); >> >

Catching Exceptions in Java with finally

If you catching exceptions in Java with finally, It is executed whether an exception is handled or not. The finally block is always executed. In the following example you can learn how to use catching exceptions in Java with finally

Catching Exceptions in java with finally

/* Catching Exceptions in java with finally Example Save with file name ExceptionExample5.java */ public class ExceptionExample5 < public static void main(String args[]) < try < System.out.println("try Block Executed"); >catch(ArithmeticException ae) < System.out.println("catch Block Executed"); >finally < System.out.println("finally block always Executed"); >> >

Throwing Exceptions with throw keyword

Java allows you to throw exceptions (generate exceptions). An exception you throw is an object.

Java Exception Example with throw keyword

/* Java Exception Example with throw keyword Save with file name ExceptionExample6.java */ public class ExceptionExample6 < public static void main(String args[]) < try < int value = 0; if(value == 0) < throw new Exception("Value Should not Zero!"); >System.out.println("No Exception Occurred"); > catch(Exception ex) < System.out.println(ex); >> >

Rules in Java Exception Handling

  • A method is required to either catch or list all exceptions it might throw
    — Except for Error or RuntimeException, or their subclasses
  • If a method may cause an exception to occur but does not catch it, then it must say so using the throws keyword
    — Applies to checked exceptions only
Читайте также:  Network classes in java

Checked exception in Java

  • Java compiler checks if the program either catches or lists the occurring checked exception
  • If not, compiler error will occur

Unchecked exceptions in Java

  1. Not subject to compile-time checking for exception handling
  2. Built-in unchecked exception classes Error, RuntimeException and Their subclasses
  3. Handling all these exceptions may make the program cluttered and may become a nuisance

Creating Your Own Exception Class

Steps to follow

  1. Create a class that extends the RuntimeException or the Exception class
  2. Customize the class i.e. Members and constructors may be added to the class

How To Use Your Own Exceptions in Java ?

The following example shows how to use your own exceptions in java.

Java Exception Example with Your Own Exceptions

/* Java Exception Example with Your Own Exceptions Save with file name MyOwnException.java */ public class MyOwnException extends Exception < String msg = null; public MyOwnException(String msg) < super(msg); this.msg = msg; >public String printWhatHappened() < if(msg == null) return ""; else return msg; >>

Java Exception Example with Your Own Exception with throw keyword

/* Java Exception Example 7 Save with file name ExceptionExample7.java */ public class ExceptionExample7 < public static void main(String args[]) < try < int value = 0; if(value == 0) < throw new MyOwnException("Value Should not Zero!"); >System.out.println("No Exception Occurred"); > catch(MyOwnException ex) < System.out.println(ex.printWhatHappened()); >> >

Conversion Errors

Exception in thread «main» error : conversion = ‘%’

You will get this error, when you put ‘%’ at wrong place in your code like following method.

In the above error code we are swapped the order of the letter s with the sign % on the last one. So if you correct the error you should change s% to %s in your code like below code.

Java Collections Framework Java double Array The Python Tutorial How to store byte array in MySQL using Java Python Keywords Java Arrays Java JDBC Tutorial - Java Database Connectivity HTML5 Tutorial Python Data Types How to store byte array in SQL Server using Java Happy Father Java Basics 9 Best Father’s Day 2023 Gifts Java byte Array what is coronavirus covid-19 HTML5 Tags Tutorial Father

© 2010 — 2023 HudaTutorials.com All Rights Reserved.

Источник

Error code handling 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

Источник

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