Categories: Java

throw, throws & finally

The Java keywords for managing exceptions include throw, throws, and finally.

throw keyword:

To throw an exception explicitly in Java, use the throw keyword.

The exception object that is to be thrown is specified. The notice that comes with the exception contains a description of the error. These anomalies could be caused by user inputs, the server, etc.

Java’s throw keyword allows us to throw either verified or unchecked exceptions. It mostly serves as a custom exception thrower.

Syntax:
throw new exception_class("error message");  
Example of throw Exception:
public class Demo {   
    //function to check if a student passed or failed   
    public static void validate(int percent) {  
        if(percent<30) {  
             
            throw new ArithmeticException("Student Failed");    
        }  
        else {  
            System.out.println("Student Passed!!");  
        }  
    }  
    //main method  
    public static void main(String args[]){  
        //calling the function  
        validate(33);  
        System.out.println("\n---------");    
  }    
}    
Output:

When percent is 33%.

Student Passed!!
---------

When percent is 28%. The exception is successfully handled.

Exception in thread "main" java.lang.ArithmeticException: Student Failed
 at Demo.validate(Demo.java:6)
 at Demo.main(Demo.java:15)
throws Keyword:

Declaring an exception in Java requires the throws keyword. The programmer receives a notification that an exception might happen. Therefore, the programmer should provide the exception handling code to retain the program’s usual flow.

The checked exceptions are often handled through exception handling. It is the responsibility of the programmer to check the code before using it if an unchecked exception like NullPointerException occurs.

Syntax:
return_type method_name() throws exception_class_name{  
//method code  
}  
Example of throws Keyword:
// Java program to demonstrate working of throws
class Demo {
 
    
    static void fun() throws IllegalAccessException
    {
        System.out.println("Inside fun(). ");
        throw new IllegalAccessException("demo");
    }
 
    // This is a caller function
    public static void main(String args[])
    {
        try {
            fun();
        }
        catch (IllegalAccessException e) {
            System.out.println("caught in main.");
        }
    }
}
Output:
Inside fun(). 
caught in main.
finally block:

The finally block in Java is used to run crucial code, such as connection closure, among other things.

Whether an exception is handled or not, the Java finally block is always run. Therefore, regardless of whether an exception happens or not, it contains all the relevant statements that must be printed.

The try-catch block is followed by the finally block.

Example of finally block:
// Java program to demonstrate working of try,
// catch and finally

class Demo {
 public static void main(String[] args)
 {
  int a = 10, b = 5, c = 5, result;
  try {
   result = a / (b - c);
   System.out.println("result" + result);
  }

  catch (ArithmeticException e) {
   System.out.println("Exception caught:Division by zero");
  }

  finally {
   System.out.println("I am in final block");
  }
 }
}
Output:
Exception caught:Division by zero
I am in final block

Note: also read about the Nested try block & try with Resource Statement

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago