Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Handle an IOException in Java?
Next article icon

How to Handle an IOException in Java?

Last Updated : 15 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

An IOException in Java occurs when we try to perform some input or output tasks and then some issues occur. Programmers need to handle this issue explicitly with a piece of code that executes when an issue occurs. There is an entire class for handling such issues known as the IOException class, which falls under the Java.io package.

Reasons Occurring IOException

Some common reasons why IOException takes place are:

  1. File not found.
  2. False user input.
  3. Bad URL for downloading files.
  4. File permission causes.
  5. Input/Output device issues.

Example:

Java
// Java code to illustrate IOException import java.io.*;  // Driver Class public class Main {     // Main Function     public static void main(String[] args) throws IOException     {         // FileReader object         FileReader file = new FileReader("file.txt");          // Trying to read a file that doesn't exists         System.out.println(file.read());     } } 

Output:

Exception in thread "main" java.io.FileNotFoundException: file.txt (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112)
at java.base/java.io.FileReader.<init>(FileReader.java:60)
at Main.main(Main.java:12)

How to Handle IOException?

IOExceptions can be handled explicitly using try-catch and finally blocks. The code that may contain an exception must be written inside the try block; code handling exceptions should be written inside the catch block; and finally, the block contains the piece of code that must be executed irrespective of the occurrence of any issue. Note that use of final block is not a must, It must be used as per the requirement, while try-catch block are must. There can be one try block having multiple catch blocks as well. Now, let us discuss the syntax for using these blocks.

Syntax: IOException can be handelled using try-catch and finally blocks. The basic syntax for using these blocks is:

try{
// Code where Exception may occur
}catch(Exception e){
// Piece of code to handle issue
}finally{
// Code that must be execute no matter issue occurred or not
}

Example:

Java
// Java code to illustrate IOException import java.io.*;  // Driver Class public class Main {     // Main Function     public static void main(String[] args) throws IOException     {         // Code that may contain exception must be written         // inside try block         try {             // FileReader object             FileReader file = new FileReader("file.txt");              // Trying to read a file that doesn't exists             System.out.println(file.read());         }                // Code to handle exception must be inside catch         // block         catch (Exception exp) {             // Piece of code to handle issue              // Printing error             System.out.println("Error occured: "                                + exp.getMessage());         }                // Code that must be executed always         finally {             // Code that must be executed             System.out.println(                 "Finally block will always executed, irrespective of occurence of issue");         }     } } 

Output
Error occured: file.txt (No such file or directory)  Finally block will always executed, irrespective of occurence of issue      

Explanation of the above Program:

In previous code, when we were trying to open a file which didn't exist, we got an error that was automatically handled by the IOException class (as we used the throws keyword along with the IOException class). But in this code, we tried to handle the exception explicitly by catching it. The try block contains the same code that we wrote to read a file previously. This time, when an issue occurred, the flow of the programme went inside the catch block, where code could be written to handle that exception. Along with this, using the finally block is not necessary; we can use it as per the requirement. The final block executes always, whether the issue occurs or not. Same, in this code, a file not found exception occurs, then code inside the catch block is executed, and at last, the code present inside the final block is executed.


Next Article
How to Handle an IOException in Java?

P

pradeep6036ymca
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-Exceptions
  • Java-Exception Handling
  • Java Examples
Practice Tags :
  • Java

Similar Reads

    How to handle a java.lang.IndexOutOfBoundsException in Java?
    In Java programming, IndexOutOfBoundsException is a runtime exception. It may occur when trying to access an index that is out of the bounds of an array. IndexOutOfBoundsException is defined as the RuntimeException. It can be used to find the out-of-bound run-time errors of an array. It is a part of
    2 min read
    How to Handle SQLException in JDBC?
    Java Database Connectivity (JDBC) serves as the backbone for Java applications when interacting with databases. While establishing connections and executing queries, we developers often encounter SQLExceptions, which are inevitable in the real world. Handling those exceptions is crucial in the devel
    4 min read
    How to Handle Network Timeouts and Retries in Java?
    In Java, handling network timeouts and retries can be achieved the using different libraries and techniques. One common approach involved using built-in classes such as "HttpURLConnection" or external libraries such as Apache HttpClient. By setting appropriate timeouts and implementing the retry log
    3 min read
    How to Solve IllegalArgumentException in Java?
    An unexpected event occurring during the program execution is called an Exception. This can be caused due to several factors like invalid user input, network failure, memory limitations, trying to open a file that does not exist, etc.  If an exception occurs, an Exception object is generated, contai
    3 min read
    How to Handle a java.lang.ArithmeticException in Java?
    In Java programming, the java.lang.ArithmeticException is an unchecked exception of arithmetic operations. This means you try to divisible by zero, which raises the runtime error. This error can be handled with the ArthmeticException. ArithmeticException can be defined as a runtime exception that ca
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences