Checked exception and unchecked exceptions in java
- The basics of TOGAF certification and some ways to prepare TOGAF offers architects a chance to learn the principles behind implementing an enterprise-grade software architecture, including.
- Haskell vs. PureScript: The difference is complexity Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .
- A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
- Postman API platform will use Akita to tame rogue endpoints Akita’s discovery and observability will feed undocumented APIs into Postman’s design and testing framework to bring them into .
- How to make use of specification-based test techniques Specification-based techniques can play a role in efficient test coverage. Choosing the right techniques can ensure thorough .
- GitHub Copilot Chat aims to replace Googling for devs GitHub’s public beta of Copilot Chat rolls out GPT-4 integration that embeds a chat assistant into Visual Studio, but concerns .
- Navigate multi-cloud billing challenges Keeping track of cloud bills from multiple clouds or accounts can be complex. Learn how to identify multi-cloud billing .
- 5 Google Cloud cost optimization best practices Cost is always a top priority for enterprises. For those considering Google Cloud, or current users, discover these optimization .
- How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
- BrightTALK @ Black Hat USA 2022 BrightTALK’s virtual experience at Black Hat 2022 included live-streamed conversations with experts and researchers about the .
- The latest from Black Hat USA 2023 Use this guide to Black Hat USA 2023 to keep up on breaking news and trending topics and to read expert insights on one of the .
- API keys: Weaknesses and security best practices API keys are not a replacement for API security. They only offer a first step in authentication — and they require additional .
- AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
- Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
- Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .
Checked exception and unchecked 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
Java Checked vs Unchecked Exceptions
In this Java exceptions tutorial, learn what an exception is in Java, and the difference between a checked exception and an unchecked exception. We will also learn some Java exception handling best practices.
1. What is Exception in Java?
“An exception is an unexpected event that occurred during the execution of a program, and disrupts the normal flow of instructions.”
- In Java, all errors and exceptions are of type with Throwable class.
- When an error occurs within a method, the method creates an object (or any subtype of Throwable ) and hands it off to the runtime system. This object is called the exception object.
- The exception object contains information about the error, including the exception type and the program’s state when the error occurred.
- Creating an exception object and handing it to the runtime system is called throwing an exception.
A few examples of an exception in the program execution can be:
- The user enters alphanumeric input, and the program excepts numeric input.
- The program tries to read the file, but the file does not exist in the specified location.
- A network connection terminated while reading data from a webservice.
try < Integer.parseInt("six") ; //This line throws an exception >catch(NumberFormatException nfe) < //handle exception >
2. Handling a Thrown Exception
We have two choices when an exception object is created in our application;
- Either we will handle it within the method using the try-catch block.
- Or we can pass it to the caller method to let it handle.
This is a very important decision to be made while setting the responsibilities of a method.
A method should clearly indicate what exceptions it will handle and which it will not. It is defined in the method declaration using the throws keyword.
To handle the exception, We must catch the exception in catch section of try-catch block.
If an exception is not handled in the application, then it will propagate to the JVM. The JVM usually terminates the program.
3. Checked Exception vs Unchecked Exception
In Java, exceptions are broadly categorized into two sections:
The checked exceptions are those exceptions, as the name suggests, which a method must handle in its body or throw to the caller method so the caller method can handle it.
Checked exceptions are checked by the Java compiler, so they are called compile-time exceptions.
Java compiler forces us to handle these exceptions in some manner in the application code. We must handle these exceptions at a suitable level inside the application to inform the user about the failure and ask him to retry or come later.
Generally, checked exceptions denote error scenarios outside the program’s immediate control. These usually occur when the program interacts with other systems/network resources e.g. database errors, network connection errors, missing files, etc.
Note that all checked exceptions are subclasses of Exception class. For example,
Checked Exception Example
The FileNotFoundException is a checked exception in Java. Anytime, we want to read a file from the filesystem, Java forces us to handle an error situation where the file may not be present in the place.
public static void main(String[] args)
In the above example, you will get compile-time error with the message – Unhandled exception type FileNotFoundException .
To make the program able to compile, we must handle this error situation in the try-catch block. Below given code will compile absolutely fine.
public static void main(String[] args) < try < FileReader file = new FileReader("somefile.txt"); >catch (FileNotFoundException e) < //Alternate logic e.printStackTrace(); >>
Unchecked exceptions are not checked by the compiler. These are called runtime exceptions. Unchecked exceptions will come into life and occur in the program, once any buggy code is executed.
In Java, the compiler does not force a member method to declare the unchecked exceptions into the method declaration. Generally, such methods almost always do not declare them.
Unchecked Exceptions are subclasses of RuntimeException class.
The strange thing is that RuntimeException is itself subclass of Exception i.e. all unchecked exception classes should have been checked exceptions implicitly, BUT they are not.”
Unchecked Exception Example
The code in the given program does not give any compile-time error. But when we run the example, it throws NullPointerException . NullPointerException is an unchecked exception in Java.
public static void main(String[] args) < try < FileReader file = new FileReader("pom.xml"); file = null; file.read(); >catch (IOException e) < //Alternate logic e.printStackTrace(); >>
4. Exception Handling Best Practices
- Checked exceptions can be used when a method may fail to do what it must. For example, a method named prepareSystem() that pre-populates configuration files and does some configuration using them. It can declare throwing FileNotFoundException, which implies that the method uses configuration files from the file system and they are missing.
- Ideally, checked exceptions should never be used for programming errors but should absolutely be used for resource errors and flow control in such cases.
- Throw only those exceptions that a method can not handle by any means. The method should first try to handle it as soon as it encounters it. Throw the exception only if it is impossible to handle it inside the method.
- A good way to define method signatures is to declare exceptions close to method name. If the method is named openFile() , then it is expected to throw FileNotFoundException ?. If the method is named findProvider() , then it is expected to throw NoSuchProviderException .
- Also, these types of exceptions should be checked as it forces the caller to deal with the problems inherent to the semantics of the methods.
- If we are creating any custom exception, then the rule is if a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
In this Java tutorial, we learned about Java exceptions. We learned the difference between checked vs unchecked exceptions in Java and how to handle unchecked exceptions and exception hierarchy in Java with examples.
Remember, the biggest difference between checked and unchecked exceptions is that checked exceptions are forced by the compiler and used to indicate exceptional conditions that are out of the program’s control, while unchecked exceptions occur during runtime and are used to indicate programming errors.