Java Synchronization Tutorial : What, How and Why? Read more: http://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html#ixzz3ilDfAUs9

Multit-hreading and synchronization is a very important topic for any Java programmer. Good knowledge of multithreading, synchronization, and thread-safety can put you in front of other developers, at same time it’s not easy to master these concept. In fact writing correct concurrent code is one of the hardest thing, even in Java, which has several inbuilt synchronization utilities. In this Java synchronization tutorial we will learn what is meaning of Synchronization in Java, Why do we need Synchronization in Java, What is java synchronized keyword, examples of using Java synchronized method and blocks, What can happen in multithreading code in absence of synchronized constructs, tips to avoid mistakes, while locking critical section in Java and some of importantpoints about synchronization in Java. Since Java provides different constructs to provide synchronization and locking e.g. volatile keyword, atomic variable, explicitly locking using java.util.concurrent.lock.Lock interface and there popular implementations e.g. ReentrantLock and ReentrantReadWriteLock, It becomes even more important to understand difference between synchronized and other constructs. Remember, clear understanding of synchronization is must to write correct concurrent code in Java, which is free of multithreading issues like deadlock, race conditions and thread-safety. I am sure, things learned in this Java synchronization tutorial will help. Once you gone through this article, You can further read Java Concurrency in Practice to develop your concept.  That’s the one of those book which every Java developer must read.

What is Synchronization in Java

Synchronization in Java is an important concept since Java is a multi-threaded language where multiple threads run in parallel to complete program execution. In multi-threaded environment synchronization of Java object or synchronization of Java class becomes extremely important. Synchronization in Java is possible by using Java keywords “synchronized” and “volatile”. Concurrent access of shared objects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these errors you need to properly synchronize your Java object to allow mutual exclusive access of critical section to two threads. By the way This Java Synchronization tutorial is in continuation of my article How HashMap works in Java  and difference between HashMap and Hashtable in Java  if you haven’t read already you may find some useful information based on my experience in Java Collections.

Why do we need Synchronization in Java?

If your code is executing in multi-threaded environment, you need synchronization for objects, which are shared among multiple threads, to avoid any corruption of state or any kind of unexpected behavior. Synchronization in Java will only be needed if shared object is mutable. if your shared object is either read only or immutable object, than you don’t need synchronization, despite running multiple threads. Same is true with what threads are doing with object if all the threads are only reading value then you don’t require synchronization in Java. JVM guarantees that Java synchronized code will only be executed by one thread at a time. In Summary Java synchronized Keyword provides following functionality essential for concurrent programming :

1) synchronized keyword in Java provides locking, which ensures mutual exclusive access of shared resource and prevent data race.

2) synchronized keyword also prevent reordering of code statement by compiler which can cause subtle concurrent issue if we don’t use synchronized or volatile keyword.

3) synchronized keyword involve locking and unlocking. before entering into synchronized method or block thread needs to acquire the lock, at this point it reads data from main memory than cache and when it release the lock, it flushes write operation into main memory which eliminates memory inconsistency errors.

Synchronized keyword in Java

Prior to Java 1.5 synchronized keyword was only way to provide synchronization of shared object in Java. Any code written by using  synchronized block or enclosed inside synchronized method will be mutually exclusive, and can only be executed by one thread at a time. You can have both static synchronized method and non static synchronized method and synchronized blocks in Java but we can not have synchronized variable in java. Using synchronized keyword with variable is illegal and will result in compilation error. Instead of synchronized variable in Java, you can have java volatile variable, which will instruct JVM threads to read value of volatile variable from main memory and don’t cache it locally. Block synchronization in Java is preferred over method synchronization in Java because by using block synchronization, you only need to lock the critical section of code instead of whole method. Since synchronization in Java comes with cost of performance, we need to synchronize only part of code which absolutely needs to be synchronized.

Example of Synchronized Method in Java

Using synchronized keyword along with method is easy just apply synchronized keyword in front of method. What we need to take care is that static synchronized method locked on class object lock and non static synchronized method locks on current object (this). So it’s possible that both static and non static java synchronized method running in parallel.  This is the common mistake a naive developer do while writing Java synchronized code.

public class Counter{ private static int count = 0; public static synchronized int getCount(){ return count; } public synchoronized setCount(int count){ this.count = count; } }

In this example of Java synchronization code is not properly synchronized because both getCount() and setCount() are not getting locked on same object and can run in parallel which may results in incorrect count. Here getCount() will lock inCounter.class object while setCount() will lock on current object (this). To make this code properly synchronized in Java you need to either make both method static or non static or use java synchronized block instead of java synchronized method.By the way this is one of the common mistake Java developers make while synchronizing their code.

Example of Synchronized Block in Java

Using synchronized block in java is also similar to using synchronized keyword in methods. Only important thing to note here is that if object used to lock synchronized block of code, Singleton.class in below example is null then Java synchronized block will throw a NullPointerException.

public class Singleton{ private static volatile Singleton _instance; public static Singleton getInstance(){ if(_instance == null){ synchronized(Singleton.class){ if(_instance == null) _instance = new Singleton(); } } return _instance; }

This is a classic example of double checked locking in Singleton. In this example of Java synchronized code, we have made only critical section (part of code which is creating instance of singleton) synchronized and saved some performance. If you make wholemethod synchronized than every call of this method will be blocked, while you only need blocking to create singleton instance on first call. By the way, this is not the only way to write threadsafe singleton in Java. You can use Enum, or lazy loading to avoid thread-safety issue during instantiation. Even above code will not behave as expected because prior to Java 1.5, double checked locking was broker and even with volatile variable you can view half initialized object. Introduction of Java memory model and happens before guarantee in Java 5 solves this issue. To read more about Singleton in Java see that.

Important points of synchronized keyword in Java

  1. Synchronized keyword in Java is used to provide mutual exclusive access of a shared resource with multiple threads in Java. Synchronization in Java guarantees that, no two threads can execute a synchronized methodwhich requires same lock simultaneously or concurrently.
  1. You can use java synchronized keyword only on synchronized method or synchronized block.
  1. When ever a thread enters into java synchronized method or block it acquires a lock and whenever it leaves java synchronized method or block it releases the lock. Lock is released even if thread leaves synchronizedmethod after completion or due to any Error or Exception.
  1. Java Thread acquires an object level lock when it enters into an instance synchronized java method and acquires a class level lock when it enters into static synchronized java method.
  1. Java synchronized keyword is re-entrant in nature it means if a java synchronized method calls another synchronized method which requires same lock then current thread which is holding lock can enter into that method without acquiring lock.
  1. Java Synchronization will throw NullPointerException if object used in java synchronized block is null e.g. synchronized (myInstance) will throws java.lang.NullPointerException if myInstance is null.
  1. One Major disadvantage of Java synchronized keyword is that it doesn’t allow concurrent read, which can potentially limit scalability. By using concept of lock stripping and using different locks for reading and writing, you can overcome this limitation of synchronized in Java. You will be glad to know that java.util.concurrent.locks.ReentrantReadWriteLock provides ready made implementation of ReadWriteLock in Java.
  1. One more limitation of java synchronized keyword is that it can only be used to control access of shared object within the same JVM. If you have more than one JVM and need to synchronized access to a shared file system or database, the Javasynchronized keyword is not at all sufficient. You need to implement a kind of global lock for that.
  1. Java synchronized keyword incurs performance cost. Synchronized method in Java is very slow and can degrade performance. So use synchronization in java when it absolutely requires and consider using java synchronized block for synchronizing critical section only.
  1. Java synchronized block is better than java synchronized method in Java because by using synchronized block you can only lock critical section of code and avoid locking whole method which can possibly degrade performance. A good example of java synchronization around this concept is getInstance() method Singleton class. See here.
  1. Its possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object.
  1. From java 5 after change in Java memory model reads and writes are atomic for all variables declared using volatile keyword (including long and double variables) and simple atomic variable access is more efficient instead of accessing these variables via synchronized java code. But it requires more care and attention from the programmer to avoid memory consistency errors.
  1. Java synchronized code could result in deadlock or starvation while accessing by multiple thread if synchronization is not implemented correctly. To know how to avoid deadlock in java see here.
  1. According to the Java language specification you can not use Java synchronized keyword with constructor it’s illegal and result in compilation error. So you can not synchronized constructor in Java which seems logical because other threads cannot see the object being created until the thread creating it has finished it.
  1. You cannot apply java synchronized keyword with variables and can not use java volatile keyword with method.
  1. Java.util.concurrent.locks extends capability provided by java synchronized keyword for writing more sophisticated programs since they offer more capabilities e.g. Reentrancy and interruptible locks.
  1. Java synchronized keyword also synchronizes memory. In fact java synchronized synchronizes the whole of thread memory with main memory.
  1. Important method related to synchronization in Java are wait(), notify() and notifyAll() which is defined in Object class. Do you know, why they are defined in java.lang.object class instead of java.lang.Thread? You can find some reasons, which make sense.
  2. Do not synchronize on non final field on synchronized block in Java. because reference of non final field may change any time and then different thread might synchronizing on different objects i.e. no synchronization at all. example of synchronizing on non final field :

private String lock = new String(“lock”); synchronized(lock){ System.out.println(“locking on :” + lock); }

any if you write synchronized code like above in java you may get warning “Synchronization on non-final field”  in IDE like Netbeans and InteliJ

  1. Its not recommended to use String object as lock in java synchronized block because string is immutable object and literal string and interned string gets stored in String pool. so by any chance if any other part of code or any third party library used same String as there lock then they both will be locked on same object despite being completely unrelated which could result in unexpected behavior and bad performance. instead of String object its advised to use new Object() for Synchronization in Java on synchronized block.

private static final String LOCK = “lock”; //not recommended private static final Object OBJ_LOCK = new Object(); //better public void process() { synchronized(LOCK) { …….. } }

  1. From Java library Calendar and SimpleDateFormat classes are not thread-safe and requires external synchronization in Java to be used in multi-threaded environment.

Probably most important point about Synchronization in Java is that, in the absence of synchronized keyword or other construct e.g. volatile variable or atomic variable, compiler, JVM and hardware are free to make optimization, assumption, reordering or caching of code and data, which can cause subtle concurrency bugs in code. By introducing synchronization by using volatile, atomic variable or synchronized keyword, we instruct compiler and JVM to not to do that.
Update 1: Recently I have been reading several Java Synchronization and Concurrency articles in internet and I come across jeremymanson’s blog which works in google and has worked on JSR 133 Java Memory Model, I would recommend some of this blog post for every java developer, he has covered certain details about concurrent programming , synchronization and volatility in simple and easy to understand language, here is the link atomicity, visibility and ordering.

Update 2:  I am grateful to my readers, who has left some insightful comments on this post. They have shared lots of good information and experience and to provide them more exposure, I am including some of there comments on main article, to benefit new readers.

@Vikas wrote
Good comprehensive article about synchronized keyword in Java. to be honest I have never read all these details about synchronized block or method at one place. you may want to highlight some limitation of synchronized keyword in Java which is addressed by explicit locking using new concurrent package and Lock interface :

1. synchronized keyword doesn’t allow separate locks for reading and writing. as we know that multiple thread can read without affecting thread-safety of class, synchronized keyword suffer performance due to contention in case of multiple reader and one or few writer.

2. if one thread is waiting for lock then there is no way to time out, thread can wait indefinitely for lock.

  1. on similar note if thread is waiting for lock to acquired there is no way to interrupt the thread.

All these limitation of synchronized keyword is addressed and resolved by using ReadWriteLock and ReentrantLock in Java 5.

@George wrote
Just my 2 cents on your great list of Java Synchronization facts and best practices :
1) synchronized keyword in internally implemented using two byte code instructions MonitorEnter and MonitorExit, this is generated by compiler. Compiler also ensures that there must be a MonitorExit for every MonitorEnter in different code path e.g. normal execution and abrupt execution, because of Exception.

2) java.util.concurrent package different locking mechanism than provided by synchronized keyword, they mostly used ReentrantLock, which internally use CAS operations, volatile variables and atomic variables to get better performance.
3) With synchronized keyword, you have to leave the lock, once you exist a synchronized method or block, there is no way you can take the lock to other method. java.util.concurrent.locks.ReentrantLock solves this problem by providing control for acquiring and releasing lock, which means you can acquire lock in method A and can release in method B, if they both needs to be locked in same object lock. Though this could be risky as compiler will neither check nor warn you about any accidental leak of locks. Which means, this can potentially block other threads, which are waiting for same lock.

4) Prefer ReentrantLock over synchronized keyword, it provides more control on lock acquisition, lock release and better performance compared to synchronized keyword.
5) Any thread trying to acquire lock using synchronized method will block indefinitely, until lock is available. Instead this, tryLock() method of java.util.concurrent.locks.ReentrantLock will not block if lock is not available.
Having said that, I must say, lots of good information.

Recommend Books to learn Synchronization and Concurrency in Java

Synchronization and Concurrency is complex topic in Java and it’s not easy to master them. Even more experienced Java developers struggle to write correct concurrent code in Java. I would highly recommend following Java books to master multi-threading, synchronization and Concurrency.

Read more: http://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html#ixzz3ilDqjVzf

Advertisement

Motherboard Port Guide: Solving Your Connector Mystery

If you’ve ever opened a PC case and stared inside, or looked at a bare motherboard, you may be taken aback by the number and variety of connectors, pins, and slots that exist on a modern PC motherboard. In this guide I’ll identify some of the most common (and a few uncommon) connectors on motherboards used in most home PCs. I won’t cover server- or workstation-class boards here, just what you might find in a typical midrange or high-end home PC.

For a similar discussion of the ports that you’re likely to encounter on the exterior of a PC case, see “Multiple Ports on Your PC: What Do They Do for You?

Since no single motherboard contains every type of connectors, I’ve used photos of four different boards to illustrate key examples. In one or two instances, there is some overlap; but for the most part, connectors are mentioned only once. Many of them may exist across different motherboard designs, however.

ADVERTISING

Asus P5WDH Deluxe

Let’s start with an older motherboard, an Asus P5WDH Deluxe. This motherboard has a few connectors that aren’t included on current-generation boards, as wll as some that do are still included, but are more readily visible here.

Connections on an older Asus P5WDH Deluxe motherboard.

Audio front panel: This ten-pin connector links to the front-panel headphone and microphone inputs. The particular connector shown is an AC97 connector, which existed prior to multichannel HD audio. It’s still in common use today.

Azalia digital audio header: You rarely find this connector, used to tie the motherboard to multichannel digital outputs on the case, on current motherboards.

Serial-port header: This connector isn’t physically present on the board shown–you can just see the solder points for it. But this header does appear on a few modern boards. It supports a nine-pin, RS-232 serial port, usually as a bracket that occupies a slot space on the back of the case. A number of RS-232 connections remain in use today, mostly in point-of-sale devices or specialized test instruments. Consumer boards typically don’t have them.

FireWire (IEEE 1994a): Once common as a digital camcorder interface, FireWire has largely been supplanted by USB, and the motherboard makers are gradually phasing it out. Some professional audio hardware still uses FireWire, though; you may also occasionally find higher-speed IEEE 1394b headers, but they are even rarer.

USB 2.0 front panel: These connectors are used to link to the front-panel USB ports on PC cases.

SATA connectors: These components connect via cables to various storage devices, including hard-disk drives, solid-state drives, and optical drives.

IDE connector: Rarely found today, IDE connectors were used to link to older hard drives. In addition, until a couple of years ago, many optical drives supported IDE. Today, all new storage devices ship with SATA.

Floppy disk connector: The venerable 3.5-inch floppy disk drive survived for nearly two decades–an eternity in the tech universe. But unless you have a pile of old floppies, you won’t need a floppy drive. And if you do find yourself needing a floppy drive, you can always pick up an external, USB-connected drive.

Intel DP67BG

Now let’s examine a more recent motherboard: an Intel D67BG, based on Intel’s P67 chipset and supporting LGA 1155 CPUs (like the Sandy Bridge-based Core i7-2600K).

Intel D67BG motherboard: a modern Intel design.

DDR3 memory sockets: Current-generation PC systems use DDR3 memory, but in many instances they support different operating speeds. The P67 chipset used in this board maxes out at DDR3-1600, but to achieve that level of speed you’d have to overclock the chipset–officially the P67 supports only DDR3-1333. Here, we see four memory sockets. The system supports dual-channel memory, meaning that the system is populated with paired memory modules, which are mounted in sockets of the same color.

CPU fan header: This connector is specifically designed to link to the CPU cooling fan. The system BIOS monitors CPU cooling fan speeds; and if the fan isn’t connected to this header, you may get an error at bootup.

Eight-pin ATX12V (CPU power) connector: Back when the Pentium 4 processor first shipped, Intel realized that high-performance CPUs needed their own source of clean, dedicated power beyond what the standard 24-pin power connector could deliver. Thus was born ATX12V. You’ll see four-pin connectors on lower-end boards supporting CPUs with lower thermal design power (TDP), but the eight-pin version of the connector is used with higher-end processors and on boards that users may overclock.

Power for secondary fans: Many motherboards with secondary-fan power headers; these connectors are mainly used to power and monitor various case fans.

PCI Express x1 connector: PCI Express is a serial interface, though multiple lanes may be ganged together. The “x1” refers to a slot supporting a single PCI Express lane; it is used for I/O devices that don’t require bidirectional bandwidth greater than 500 megabytes per second (gen 1 PCIe). Sound cards, for example, are typically PCIe x1 devices.

PCI Express x16 (graphics): PCI Express x16 slots are used mostly for graphics cards, though they can be used with any PCI Express card. Confusion may arise, however, because not all PCIe x16 slots are true PCIe x16. Occasionaly, you’ll see PCIe x16 connectors that are physical slots for accommodating graphics cards, but are actually eight-lane (x8) or even four-lane (x4) electrically.

On some boards, even slots that support true 16-lane PCI Express for graphics may revert to eight lanes if you install a second graphics card into a second PCIe x16 slot on the motherboard. The P67 chipset, for instance, has only 16 total PCIe lanes for graphics. So if you drop in two graphics cards to run in dual GPU mode, each card will have just eight lanes available to it. This situation isn’t as bad as it sounds, though, since even eight lanes in a PCIe 2.0- or 3.0-based system delivers plenty of bandwidth for most games.

32-bit legacy PCI slot: The now-classic 32-bit PCI slot has been around since 1993. A host of expansion cards support 32-bit PCI; and to accommodate them, most motherboards are likely to have at least one 32-bit PCI slot going forward. You may see some system boards configured so that a particular back-panel case bracket can support either a PCI slot or a PCIe slot, with some overlap between the two because they’re very close together.

Front-panel switch header: This header connects various wires to the front panel of the case, where they link to power and reset buttons, and status LEDs for power and storage-drive activity.

Gigabyte 990FXA-UD7

Next we’ll turn our attention to a motherboard that supports AMD CPUs. Note that AMD-chipset boards support many of the same features as Intel-based boards–that’s the great thing about industry standards.

An AMD-compatible motherboard: the Gigabyte 990FXA-UD7.

24-pin ATX power: This connector exists on all current ATX-based motherboards, and is the standard means of connecting power from power supplies. This connector delivers power to all interfaces, including 3V, 5V, and 12V. The typical ATX12V version 2.3 PSU delivers up to 75W for PCI Express graphics cards; but numerous modern graphics cards need more than that, which is why you’ll often find secondary six- or eight-pin power connectors on the graphics cards themselves.

ATX4P: This unusual item is actually a SATA power connector for delivering power to SSDs, hard drives, or optical drives from the motherboard itself.

TPM connector: Some off-the-shelf PCs and laptops use the Trusted Platform Module connector to link to a cryptographic processor module for storing encryption keys and handling dedicated encryption chores such as hard-drive encryption and certain types of digital rights management (DRM) decryption.

USB 3.0 front panel: This connector is used to drive front-panel USB 3.0 connectors. It requires more pins than USB 2.0 connectors do, but it drives two USB 3.0 ports instead of one. If your PC case lacks a USB 3.0 internal cable, you won’t be able to use it. Like back-panel connectors, front-panel USB 3.0 ports are often color-coded blue.

AMD CPU socket: I’m calling out this component because its style differs from that of a modern Intel CPU socket. AMD CPUs still have pins, whereas Intel has moved the pins to the motherboard socket.

Intel DZ77GA-70K

I’m using a photo of just one section of this board, to call out some specific connectors and to get a little closer in. The Intel DZ77GA-70K motherboard is designed to accommodate the latest Intel Z77 chipset.

Part of the Intel DZ77GA-70K–a motherboard that hosts the latest Intel Z77 chipset.

Case fan header: As noted earlier, most higher-end motherboards have several of these fan headers scattered around the board. If enough of them are available, you should connect your fans to them, so that the BIOS can monitor and manage the fan speeds–unless you’re a serious overclocker who uses separate fan-control modules.

PCI Express x4 slot: This relatively rare physical and electrical PCIe x4 slot is used for higher-performance networking cards and for some storage controller cards.

S/PDIF digital audio: This older type of connector was originally used to connect to CD-ROM drives. Today it’s still used to connect to some optical drives and other audio devices that support S/PDIF (Sony/Philips Digital Interface) digital audio.

USB 3.0 front panel: The DZ77GA motherboard ships with two front-panel USB 3.0 connectors, driving up to four USB 3.0 ports on the front of the PC case.

High-current USB 2.0 front panel: This is a slightly different type of USB 2.0 connector. Though it acts as a normal USB 2.0 port when sending or receiving data, it can deliver extra current to permit fast charging of mobile devices, and it can even charge devices (like Apple’s iPad) that requires more current than standard USB 2.0 normally delivers.

Consumer IR: This connector is used to attach front-panel infrared receivers, which enable users to control the PC via a standard programmable remote.

Diagnostic LEDs: Most motherboards have simple LEDs that light up or change color if the board experiences problems. A few higher-end boards, however, have these status LEDs, which flash an alphanumeric code that helps the user narrow down the source of a boot problem.

That wraps up our tour of various motherboard connectors, pins, and ports. Though I haven’t covered all of the possibilities by any means, the ones listed here account for the vast majority of connectors you’ll encounter on today’s motherboards.

Rarely will you use every single connector on a board, but understanding these connectors should help you choose a PC case that suits your needs, or that accommodates new devices that you plan to add in an upgrade. Also, if you have a specific need, you’ll be better able to shop for a motherboard capable of handling your application.

How to throw exception in java with example

In java we have already defined exception classes such asArithmeticException, ArrayIndexOutOfBoundsException,NullPointerException etc. There are certain conditions defined for these exceptions and on the occurrence of those conditions they are implicitly thrown by JVM(java virtual machine).

Do you know that a programmer can create a new exception and throw it explicitly? These exceptions are known as user-defined exceptions. In order to throw user defined exceptions, throw keyword is being used. In this tutorial, we will see how to create a new exception and throw it in a program using throw keyword.

You can also throw an already defined exception like ArithmeticException,IOException etc.

Syntax of throw statement

throw AnyThrowableInstance;

Example:

//A void method
public void sample()
{
   //Statements
   //if (somethingWrong) then
   IOException e = new IOException();
   throw e;
   //More Statements
 }

Note:

  • A call to the above mentioned sample method should be always placed in a try block as it is throwing a checked exceptionIOException. This is how it the call to above method should be done:
    MyClass obj =  new MyClass();
    try{
          obj.sample();
    }catch(IOException ioe)
     {
          //Your error Message here
          System.out.println(ioe);
      }
  • Exceptions in java are compulsorily of type Throwable. If you attempt to throw an object that is not throwable, the  compiler refuses to compile your program and it would show a compilation error.

Flow of execution while throwing an exception using throw keyword

Whenever a throw statement is encountered in a program the next statement doesn’t execute. Control immediately transferred to catch block to see if the thrown exception is handled there. If the exception is not handled there then next catch block is being checked for exception and so on. If none of thecatch block is handling the thrown exception then a system generated exception message is being populated on screen, same what we get for un-handled exceptions.
E.g.

class ThrowDemo{
   public static void main(String args[]){
      try{
	   char array[] = {'a','b','g','j'};
	   /*I'm displaying the value which does not
	    * exist so this should throw an exception
	    */
	   System.out.println(array[78]);
      }catch(ArithmeticException e){
	    System.out.println("Arithmetic Exception!!");
       }
   }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 
78 at beginnersbook.com.ThrowDemo.main(Details.java:9)

Since the exception thrown was not handled in the catch blocks the system generated exception message got displayed for that particular exception.

Few examples of throw exception in Java

Example 1: How to throw your own exception explicitly using throw keyword

package beginnersbook.com;
class MyOwnException extends Exception {
   public MyOwnException(String msg){
      super(msg);
   }
}

class EmployeeTest {
   static void  employeeAge(int age) throws MyOwnException{
      if(age < 0)
         throw new MyOwnException("Age can't be less than zero");
      else
         System.out.println("Input is valid!!");
   }
   public static void main(String[] args) {
       try {
            employeeAge(-2);
       }
       catch (MyOwnException e) {
            e.printStackTrace();
       }
   }
}

Output:

beginnersbook.com.MyOwnException: Age can't be less than zero

Points to Note: Method call should be in try block as it is throwing an exception.

Example2: How to throw an already defined exception using throw keyword

package beginnersbook.com;
class Exception2{
   static int sum(int num1, int num2){
      if (num1 == 0)
         throw new ArithmeticException("First parameter is not valid");
      else
         System.out.println("Both parameters are correct!!");
      return num1+num2;
   }
   public static void main(String args[]){
      int res=sum(0,12);
      System.out.println(res);
      System.out.println("Continue Next statements");
   }
}

Output:

Exception in thread main java.lang.ArithmeticException: First parameter is not valid

Similarly other exceptions, such as NullPointerException,ArrayIndexOutOfBoundsException etc. can be thrown. That’s all for the topic how to throw exception in java. Let me know your feedback on this.

Throws clause in java – Exception handling

Use of throws keyword in Java

1. The throws keyword is used in method declaration, in order to explicitly specify the exceptions that a particular method might throw. When a method declaration has one or more exceptions defined using throws clause then the method-call must handle all the defined exceptions.
2. When defining a method you must include a throws clause to declare those exceptions that might be thrown but doesn’t get caught in the method.
3. If a method is using throws clause along with few exceptions then this implicitly tells other methods that – “ If you call me, you must handle these exceptions that I throw”.

Syntax of Throws in java:

void MethodName() throws ExceptionName{
    Statement1
    ...
    ...
}

E.g:

public void sample() throws IOException{
     //Statements
     //if (somethingWrong)
     IOException e = new IOException();
     throw e;
     //More Statements
}

Note: In case a method throws more than one exception, all of them should be listed in throws clause. PFB the example to understand the same.

public void sample() throws IOException, SQLException
{
    //Statements
}

The above method has both IOException and SQLException listed in throws clause. There can be any number of exceptions defined using throws clause.

Complete Example of Java throws Clause

class Demo
{
   static void throwMethod() throws NullPointerException
   {
       System.out.println ("Inside throwMethod");
       throw new NullPointerException ("Demo"); 
   } 
   public static void main(String args[])
   {
       try
       {
          throwMethod();
       }
       catch (NullPointerException exp)
       {
          System.out.println ("The exception get caught" +exp);
       }
    }
}

The output of the above program is:

Inside throwMethod
The exception get caught java.lang.IllegalAccessException: Demo