Java

Exceptions in Java

Exceptions in Java

When the flow of instructions is disrupted during the execution of the code, exceptions occur and they should be dealt with to avoid any serious circumstances. 
Java provides a rich set of classes for working with exceptions in java.lang package. These classes include 
● Exception: This is the base class for all exceptions in Java. 
● RuntimeException: This is the base class for all exceptions that occur during the execution of a program. 
● IOException: This is the base class for all exceptions related to I/O operations.

The following code reads a file and catches an IOException if the file is not found:

try { 
FileReader reader = new FileReader("example.txt"); 
// code that reads the file 
reader.close(); 
} catch (IOException e) { 
System.out.println("File not found."); 
} 

You can also throw exceptions explicitly using the "throw" keyword. 
For example, the following code throws an IllegalArgumentException if a negative value is passed to a method: 

public void setValue(int x) { 
if (x < 0) { 
throw new IllegalArgumentException("Value cannot be negative."); 
} 
// code that sets the value 
} 

To handle multiple exceptions, ‘|’ is used: 

try { 
// code that reads a file 
} catch (IOException | FileNotFoundException e) { 
System. out.println("Error reading file."); 
} 

Java also provides a way to define your own exception classes by extending the Exception class. 
Example: 

public class MyException extends Exception { 
public MyException(String message) { 
super(message); 
} 
} 

 

Top course recommendations for you

    OSI Model: Physical Layer
    2 hrs
    Beginner
    2.3K+ Learners
    4.24  (131)
    Introduction to Servlets and JSP
    2 hrs
    Beginner
    2.2K+ Learners
    4.65  (295)
    Networking in Java
    2 hrs
    Beginner
    3.1K+ Learners
    4.39  (262)
    Basics of Computer Networking
    3 hrs
    Beginner
    38.2K+ Learners
    4.43  (4194)
    Data Structures & Algorithms in Java
    4 hrs
    Beginner
    166.7K+ Learners
    4.48  (3122)
    Java Programming
    2 hrs
    Beginner
    640.4K+ Learners
    4.48  (45241)
    Python Fundamentals for Beginners
    9 hrs
    Beginner
    722.8K+ Learners
    4.55  (41113)
    Front End Development - HTML
    2 hrs
    Beginner
    505.9K+ Learners
    4.51  (40060)
    Front End Development - CSS
    2 hrs
    Beginner
    186.1K+ Learners
    4.51  (14465)
    Blockchain Basics
    3 hrs
    Beginner
    84.2K+ Learners
    4.55  (4668)