Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Java throw and throws keyword

Java throws keyword

  • The throws keyword in Java is used to declare an exception. It alerts the programmer to the possibility of an exception occurring. As a result, it is preferable for the programmer to provide exception handling code so that the program's normal flow can be maintained.
    • Exception Handling is used primarily to handle checked exceptions. If an unchecked exception occurs, such as a NullPointerException, it is the fault of the programmer for not checking the code before it is used.
    • The "throws" keyword plays a crucial role in facilitating effective exception handling. By employing this keyword, developers can convey essential information about exceptions to the method's caller.
Table Of Content

  • Java throws block
  • Problem without Java throws block
  • Example of throws block
  • Important points about throws keyword


  • When developing a program, it is essential to anticipate and address potential exceptions. The compiler acts as a proactive guard, alerting us to any potential issues and mandating the handling of checked exceptions. Failure to handle such exceptions properly will lead to a compile-time error message, insisting on either catching the unreported exception X or declaring it to be thrown.To avoid this compile-time error, we can handle the exception in two ways.
    • By using try catch
    • By using throws keyword




  • To handle Java exceptions effectively, one can utilize the "throws" keyword to transfer the responsibility of exception handling to the caller, be it a method or the Java Virtual Machine (JVM). By employing this approach, the caller method assumes the duty of appropriately managing the encountered exception.

Syntax of Java throws block

returnType methodName() throws exceptionClassName{  
    //method 
} 


Problem without Java throws block


package DockerTpoint;
public class Main {	
    public static void main(String args[]){    	  		  
        Thread.sleep(1000);
        System.out.println("Hello DockerTpoint");
   } 
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Unhandled exception type InterruptedException

	at HELLO/DockerTpoint.Main.main(Main.java:5) 

In the above program, we are getting a compile time error because there is a chance of an exception if the main thread goes to sleep, which allows other threads to execute the main() method, which causes an InterruptedException.






Java throws block


package DockerTpoint;
public class Main {	
    public static void main(String args[])throws InterruptedException{    	  		  
        Thread.sleep(1000);
        System.out.println("Hello DockerTpoint");
   } 
}

Output:

Hello DockerTpoint 

We successfully managed the InterruptedException in the previous program by employing the throws keyword, resulting in the output message "Hello DockerTpoint."




Exception handle using try-catch block


public class Main {	
    void fun() throws IllegalAccessException{
        System.out.println("fun() method ");
        throw new IllegalAccessException();
  }
  public static void main(String args[]){
    try{
        Main main=new Main();
        main.fun();
    }
    catch(IllegalAccessException e){
        System.out.println("Exception handled");
    }
  }
}




Output:

fun() method 
Exception handled 


Important points about throws keyword

  • The "throws" keyword serves a vital role in handling checked exceptions, while its usage for unchecked exceptions is irrelevant.
  • The presence of the "throws" keyword is necessary to inform the compiler about potential checked exceptions, but it does not guarantee prevention of abnormal program termination.
  • By utilizing the "throws" keyword, we can provide relevant details about the exception to the method's caller, enhancing communication and error handling.

Example of Declare Exception


package DockerTpoint;
import java.io.IOException;
class check{  
  void method()throws IOException{  
   throw new IOException("check method");  
  }  
}  
public class Main {	
   public static void main(String args[])throws IOException{ // exception declared 
	   check ch=new check();  
	   ch.method();  
  }
}




Output:

Exception in thread "main" java.io.IOException: check method
	at HELLO/DockerTpoint.check.method(Main.java:7)
	at HELLO/DockerTpoint.Main.main(Main.java:13) 

Java Throw Keyword Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
custom-exception

Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.